Skip to content Skip to sidebar Skip to footer

Selenium Python - Handling No Such Element Exception

I am writing automation test in Selenium using Python. One element may or may not be present. I am trying to handle it with below code, it works when element is present. But script

Solution 1:

Are you not importing the exception?

from selenium.common.exceptions import NoSuchElementException

try:
    elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
    elem.click()
except NoSuchElementException:  #spelling error making this code not work as expectedpass

Solution 2:

You can see if the element exists and then click it if it does. No need for exceptions. Note the plural "s" in .find_elements_*.

elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
iflen(elem) > 0
    elem[0].click()

Solution 3:

the way you are doing it is fine.. you are just trying to catch the wrong exception. It is named NoSuchElementException not nosuchelementexception

Solution 4:

Handling Selenium NoSuchExpressionException

from selenium.common.exceptions import NoSuchElementException
try:
   candidate_Name = j.find_element_by_xpath('.//span[@aria-hidden="true"]').text
except NoSuchElementException:
       try:
          candidate_Name = j.find_element_by_xpath('.//a[@class="app-aware link"]').text
       except NoSuchElementException:
              candidate_Name = "NAN"pass

Solution 5:

Why not simplify and use logic like this? No exceptions needed.

if elem.is_displayed():
    elem.click()

Post a Comment for "Selenium Python - Handling No Such Element Exception"