Search code examples
pythonseleniumif-statementtry-catchfindelement

Find element using if else or try except in Python Selenium


I am confused which is the best and correct way to check if element exists or not? Using try-except or if-else? What would be the difference and what are advantages/disadvantages of both when trying to find element?

def find_logo():
    return driver.find_elements(By.CSS_SELECTOR, ".navbar-brand [src='/logo/logo.svg']")

if find_logo(): 
    print("Found the logo")
else:
    print("Cannot find the logo")

So will get the same result with try except:

def find_logo():
    return driver.find_element(By.CSS_SELECTOR, ".navbar-brand [src='/logo/logo.svg']")

try:
    find_logo()
    print("Found the logo")
except NoSuchElementException:
    print("Cannot find the logo")

Both seem to work the same way but which is the correct way to do it?


Solution

  • Canonically both the if-else and try-except logic needs to be revamped however they needs to be implemented as per your usecase.


    if find_logo(): The if find_logo() will be always successful as in def find_logo() you have used find_elements() which may not return any elements at all. In such case you may require to check if the list size is not 0.


    try: find_logo(): try: find_logo() seems to be better organized in comarision to the other with NoSuchElementException check in place when the specific element isn't found.


    Code optimization

    However as per best practices, when looking for an element, you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following logic:

    try:
        WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".navbar-brand [src='/logo/logo.svg']")))
        print("Found the logo")
    except TimeoutException:
        print("Cannot find the logo")
        
    

    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