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?


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 import WebDriverWait
from import By
from 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.
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.
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
Answered By: Prophet
from import By
from import WebDriverWait
from import expected_conditions as EC

# initialize the web driver
driver = webdriver.Firefox()

# navigate to the website

# wait until the div is visible and contains text
wait = WebDriverWait(driver, 10)
element = wait.until(EC.text_to_be_present_in_element((By.ID, "my_div"), "some text"))

# get the text from the div
text = element.text

# close the web driver
Answered By: Achal