lundi 29 mars 2021

Wait till text in an element is changed

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

Aucun commentaire:

Enregistrer un commentaire