I'm writing tests in pytest using selenium and selenoid.
I would like to wait and see if one of two texts become visible.
something like this:
wait_for_text(text1 OR text2)
Is there any way to do this directly without using try and catch?
Using XPATH logical or
This will help to limit webdriver requests count to 1 per condition check.
wait.until(expected_conditions.presence_of_element_located((By.XPATH, "//*[(text()='text1') or (text()='text2')]")))
You can combine the two checks in a single wait()
operation - by using a python's lambda expression, using the find_elements_*()
methods glued together with an or
:
wait.until(lambda x: x.find_elements_by_xpath("//*[text()='text1']") or x.find_elements_by_xpath("//*[text()='text1']"))
For more details see the reference to original solution here
To wait for either of the texts to be visible you can induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:
Using XPath you can pass the expressions through OR
condition as follows:
element = WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH, "//*[text()='textA' or text()='textB']"))
Using XPath and lambda you can pass the expressions through OR
condition as follows:
element = WebDriverWait(driver,20).until(lambda driver: driver.find_element(By.XPATH,"//*[text()='textA']") or driver.find_element(By.XPATH,"//*[text()='textB']"))
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
You can find a couple of relevant discussions in: