Check if element exists python selenium

Nelly Kong picture Nelly Kong · Aug 15, 2017 · Viewed 41.1k times · Source

I'm trying to locate element by

element=driver.find_element_by_partial_link_text("text")

in Python selenium and the element does not always exist. Is there a quick line to check if it exists and get NULL or FALSE in place of the error message when it doesn't exist?

Answer

Andersson picture Andersson · Aug 15, 2017

You can implement try/except block as below to check whether element present or not:

from selenium.common.exceptions import NoSuchElementException

try:
    element=driver.find_element_by_partial_link_text("text")
except NoSuchElementException:
    print("No element found")

or check the same with one of find_elements_...() methods. It should return you empty list or list of elements matched by passed selector, but no exception in case no elements found:

elements=driver.find_elements_by_partial_link_text("text")
if not elements:
    print("No element found")  
else:
    element = elements[0]