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?

- 32,350
- 22
- 54
- 79

- 974
- 8
- 16
2 Answers
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

- 32,350
- 22
- 54
- 79
-
I don't have a text that I expect though, it it variable. I just want text to be present, but don't want to specify a specific text – Nicholas Hansen-Feruch Jan 26 '23 at 20:44
-
So, you mean before clicking the button no text there (even not a space!) but after the action the text content is not empty? – Prophet Jan 26 '23 at 20:46
-
exactly, the div is empty and then there is text after pressing a button – Nicholas Hansen-Feruch Jan 26 '23 at 20:50
-
how would I grab the text from the wait.until – Nicholas Hansen-Feruch Jan 26 '23 at 21:06
-
1It returns the web element, so applying `.text` on it will give you that text. I'll update the answer – Prophet Jan 26 '23 at 21:28
You could create your own custom expected condition that check for change in the text of the div
class DivTextToChange:
current_text = ''
def __call__(self, driver):
elem = driver.find_element(By.XPATH, "/html/xpath/to/div")
if elem:
text = elem.get_attribute('innerText')
if text and text != DivTextToChange.current_text:
DivTextToChange.current_text = text
return text
return False
to use:
text = WebDriverWait(driver, timeout=30).until(DivTextToChange())

- 96
- 1
- 5