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

Question:

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.

Asked By: Xtiaan

||

Answers:

Use a
‘try: except NoSuchElementException:’ statement

Answered By: Corentin Gauquier

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

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

try

from selenium.common.exceptions import NoSuchElementException

try:
    driver.find_element(By.XPATH, "/html/body/...").text
except NoSuchElementException:
    #print('no element')
    pass

Answered By: khaled koubaa

Try this, only if elements with this xpath exists, get text, else continue:

if len(driver.find_elements(By.XPATH, "/html/body/...")) > 0:
    driver.find_element(By.XPATH, "/html/body/...").text
...
Answered By: Mate Mrše

Don’t catch the raw exception.


Instead handle the desired NoSuchElementException to prevent leakage of the flaky exceptions as follows:

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