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?
CodePudding user response:
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
CodePudding user response:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# initialize the web driver
driver = webdriver.Firefox()
# navigate to the website
driver.get("http://example.com")
# 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
print(text)
# close the web driver
driver.quit()