wezzo
wezzo

Reputation: 49

How to search for an element and incase it does not exist search for another element using Selenium Python

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.

Upvotes: 3

Views: 713

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193308

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

Upvotes: 3

Related Questions