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?
Canonically both the
if-else
andtry-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 indef find_logo()
you have usedfind_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 withNoSuchElementException
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:Note : You have to add the following imports :