问题描述
请建议 Selenium 是否有一个不错的选择来等到元素内的文本发生更改.条件:
Please suggest if Selenium has a good option to wait until text will be changed within an element. Conditions:
- 页面未自动重新加载
- 动态重新加载我需要的文本的元素
- 更新此数据所需的时间未知
- 预期的文字未知.这是一个时间戳.
我编写了一个方法,它每 1 秒(或我设置的任何时间)检查一次,并在更改时获取值.但我认为可能有一些更好的选择.我尽量避免使用 time.sleep,但在目前的情况下,这是我唯一的选择.注意,此文本可能会在 5 分钟后更改,因此我需要调整重试次数 retries 或 time.sleep()另外,我使用 print 只是为了调试.
I wrote a method which checks it every 1 second (or any time I set) and gets the value when it is changed. But I think there may be some better options. I try to avoid using time.sleep, but in the current case this is the only option I came to. Note, this text may change even after 5 minutes, so I will need to adjust the number of retries retries or time.sleep() Also, I use print just for debugging.
def wait_for_text(driver): init_text = "init text" retry = 1 retries = 120 start_time = time.time() while retry <= retries: time.sleep(1) field_text = driver.find_element_by_id("my_id").text if field_text != init_text: break retry += 1 now = time.time() total_time = now-start_time print(f"Total time for text to change {total_time}") print(f"Final field value: {field_text}")
推荐答案
你可以这样做:
driver.get("https://stackoverflow.com") init_text = "Log in" from selenium.webdriver.support.wait import WebDriverWait waiter = WebDriverWait(driver=driver, timeout=120, poll_frequency=1) waiter.until(lambda drv: drv.find_element_by_class_name("login-link").text != init_text) print("Success") driver.quit()
所以你基本上是在等待一个元素停止等于给定值.
So you are basically waiting for an element stops being equal to a given value.
P.S. - 您可以通过更改开发工具中的按钮文本来测试上面的代码片段.
P.S. - You can test the snippet above by changing the button text in dev tools.