Check if python selenium element exists

I'm trying to find an item

element=driver.find_element_by_partial_link_text("text") 

in Selenium Python, and the element does not always exist. Is there a quick line to check if it exists and get NULL or FALSE instead of an error message if it does not exist?

+5
source share
1 answer

You can implement a try / except block as shown below to check if an element is present:

 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 the find_elements_...() methods. It should return you an empty list or a list of elements matched using the passed selector, but not an exception if the elements are not found:

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

Source: https://habr.com/ru/post/1270893/


All Articles