pythonseleniumxpathwebdriverwaitexpected-condition

Python selenium wait until element has text (when it didn't before)


There is a div that is always present on the page but doesn't contain anything until a button is pressed.
Is there a way to wait until the div contains text, when it didn't before, and then get the text?


Solution

  • WebDriverWait expected_conditions provides text_to_be_present_in_element condition for that.
    The syntax is as following:

    wait.until(EC.text_to_be_present_in_element((By.ID, "modalUserEmail"), "expected_text"))
    

    Afte using the following imports and initializations:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    wait = WebDriverWait(driver, 10)
    

    Used here locator By.ID, "modalUserEmail" is for example only. You will need to use proper locator matching relevant web element.
    UPD
    In case that element has no text content before the action and will have some text content you can wait for the following XPath condition:

    wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='unique_class'][text()]")))
    

    //div[@class='unique_class'] here is unique locator for that element and [text()] means that element has some text content.
    UPD2
    If you want to get the text in that element you can apply .text on the returned web element. Also, in this case it is better to use visibility_of_element_located, not just presence_of_element_located, so your code can be as following:

    the_text_value = wait.until(EC.visibility_of_element_located((By.XPATH, "//div[@class='unique_class'][text()]"))).text