Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Selenium, how to verify if element exist

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading