Selenium, how to verify if element exist

Question:

web pages could either has element with id=container_53201 or id= container_24206, but not both. I tried to verify each page has which of the element. but the following code caused the error:

No such element [id= container_24206]

if the web page has the other element. Please advise how to fix this issue.

if driver.find_element_by_id('container_53201'):
        print('Single Match') 
elif driver.find_element_by_id('container_24206'):
        print('multiple Match') 
else:
        print('Could not find')
Asked By: yyiws

||

Answers:

Instead of find_element_by_* you should use find_elements_by_*.
find_element_by_* method throws exception in case of no element found while find_elements_by_* will always return a list of matching elements. So, in case of matches it will return a non-empty list interpreted by python as Boolean True, while in case of no matches it will return an empty list interpreted by Python as a Boolean False.
So, this code should work better:

if driver.find_elements_by_id('container_53201'):
        print('Single Match') 
elif driver.find_elements_by_id('container_24206'):
        print('multiple Match') 
else:
        print('Could not find')

Also you would probably better use the modern syntax: instead of find_elements_by_id using find_elements(By.ID, **)
With it your code will look as following:

if driver.find_elements(By.ID,'container_53201'):
        print('Single Match') 
elif driver.find_elements(By.ID,'container_24206'):
        print('multiple Match') 
else:
        print('Could not find')
Answered By: Prophet
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.