How to continue if find_element does not find anything instead of producing an error that terminates the program?

I have the following code:

driver.find_element(By.XPATH, "/html/body/...").text

However, the element I am looking for is optional. It will sometimes be present and sometimes not. I want to keep track whether it is present. If it is not present, the code should not be terminated because driver.find_element throws a the NoSuchElementException error. I want to code to continue.

>Solution :

You can use try..except block to ignore if element not present

try:
   driver.find_element(By.XPATH, "/html/body/...").text
except:
   pass

Leave a Reply