3

I'm trying to search for an element and if it doesn't exist search for another element, and here is my code:

try:
    elem1 = driver.find_element_by_xpath('xpath1')
    elem = driver.find_element_by_xpath("xpath2")
    if elem.is_displayed():
        print('found 1st element')
        driver.quit()
    elif elem1.is_displayed():
        print('found 2nd element')
        driver.quit()
except NoSuchElementException:
        driver.quit()
        print('Error!')

but every time I get 'Error!', but when i try to find only one of the two elements it works properly.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
wezzo
  • 49
  • 5
  • Where in your code you are performing a search? Also if the search did not return anything what do you see on the UI? – cruisepandey Apr 06 '22 at 07:05

1 Answers1

2

The entire logic to search for an element and if not visible search for another element ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following code block:

try:
    elem1 = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//button[@class='save' and text()='save']")))
    my_text = "Found 1st element"
except TimeoutException:
    elem2 = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//button[@class='save' and text()='save']")))
    my_text = "Found 2nd element"
finally:
    print(my_text)
    driver.quit()

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
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • I think you also need to add this code: from selenium.common.exceptions import TimeoutException otherwise the TimeoutException will be deemed undefined. – toking May 04 '23 at 10:35