0

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?

user613
  • 175
  • 2
  • 10

3 Answers3

2

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')]")))
Max Daroshchanka
  • 2,698
  • 2
  • 10
  • 14
1

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

Prophet
  • 32,350
  • 22
  • 54
  • 79
1

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 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
    

Reference

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352