等到元素中的文本更改 [英] Wait till text in an element is changed

查看:32
本文介绍了等到元素中的文本更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请建议 Selenium 是否有一个好的选择来等待元素内的文本发生更改.条件:

Please suggest if Selenium has a good option to wait until text will be changed within an element. Conditions:

  • 页面不会自动重新加载
  • 动态重新加载我需要的文本元素
  • 更新此数据所需的时间未知
  • 预期文本未知.这是一个时间戳.

我编写了一个方法,它每 1 秒(或我设置的任何时间)检查一次,并在更改时获取值.但我认为可能有一些更好的选择.我尽量避免使用 time.sleep,但在目前的情况下,这是我唯一的选择.注意,这个文本即使在 5 分钟后也会改变,所以我需要调整重试次数 retriestime.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.

这篇关于等到元素中的文本更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆