Wait till text in an element is changed

Viewed 844

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

  • Page is not autoreloaded
  • Element which text I need is dynamically reloaded
  • Time required for this data to be updated is unknown
  • Expected text is unknown. It is a timestamp.

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}")
2 Answers

You can do the thing like this:

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. - You can test the snippet above by changing the button text in dev tools.

You can loop until the text change to value you want

def wait_for_text(driver):  
    init_text = "init text"
    retry = 1
    while(driver.find_element_by_id(".") != init_text ):
        retry += 1
    print(driver.find_element_by_id(".").text)
    print("number of tries: " + retry)
Related