-1

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.

Xtiaan
  • 252
  • 1
  • 11
  • That's precisely what [try/except](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) clause exists for. – matszwecja Feb 22 '23 at 13:04

4 Answers4

2

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

try:
   driver.find_element(By.XPATH, "/html/body/...").text
except:
   pass
KunduK
  • 32,888
  • 5
  • 17
  • 41
0

Use a 'try: except NoSuchElementException:' statement

0

try

from selenium.common.exceptions import NoSuchElementException

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

khaled koubaa
  • 836
  • 3
  • 14
0

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
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352