让 Selenium 等到文本可用

Make Selenium wait until text is available

我正在使用 Selenium 从该网站抓取一些数据: https://www.boerse-frankfurt.de/en/etf/ishares-core-s-p-500-ucits-etf-usd-acc

我的脚本可以运行,但我需要等待 5 秒以确保数据实际可用,否则我有时(随机)会得到空白结果。

driver.get(url)
time.sleep(5)
bid = driver.find_element_by_xpath("/html/body/app-root/app-wrapper/div/div[2]/app-etp/div[2]/div[3]/div[2]/div/div[2]/app-widget-quote-box/div/div/table/tbody/tr[3]/td[1]").text
print(bid)

我尝试使用 Selenium 的 wait 函数,但脚本运行很快,结果为空白:

driver.get(url)
try:
    bid = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH,"/html/body/app-root/app-wrapper/div/div[2]/app-etp/div[2]/div[3]/div[2]/div/div[2]/app-widget-quote-box/div/div/table/tbody/tr[3]/td[1]"))
    )
    bid = bid.text
    print(bid)
finally:
    pass

知道如何让 Selenium 等待抓取数据所需的时间吗? 谢谢


更新: 一个简单的 while 循环似乎有效:

driver.get(url)
while driver.find_element_by_xpath(xpath).text == "":
   pass
driver.find_element_by_xpath(xpath).text

有更好的方法吗?

定位 visible 元素而不是 you need to induce WebDriverWait for the and you can use either of the following :

driver.get(url)
try:
    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "/html/body/app-root/app-wrapper/div/div[2]/app-etp/div[2]/div[3]/div[2]/div/div[2]/app-widget-quote-box/div/div/table/tbody/tr[3]/td[1]"))).text)
finally:
    pass