Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Python - Handling No such element exception

Tags:

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 fails when element is not present, I want to continue to next statement if element is not present.

try:
       elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
       elem.click()
except nosuchelementexception:
       pass

Error -

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:{"method":"xpath","selector":".//*[@id='SORM_TB_ACTION0']"}
like image 614
Santhosh Avatar asked Jun 24 '16 21:06

Santhosh


People also ask

How do you pass no such element exception in selenium?

The exception occurs when WebDriver is unable to find and locate elements. Usually, this happens when the tester writes incorrect element locator in the findElement(By, by) method. with the spaces and verify using Try XPath then we can avoid this exception.

What are 5 exceptions selenium?

NoSuchFrameException: Webdriver attempts to switch to an invalid frame, which is unavailable. NoAlertPresentException: Webdriver is trying to switch to an invalid alert, which is unavailable. NoSuchWindowException: Webdriver is trying to switch to an invalid window, which is unavailable.

What are the exceptions in selenium Python?

Exceptions in Selenium Python are generally classified into two types. Checked Exception handling in Selenium is conducted while writing the code. On the other hand, Unchecked Exceptions are raised during runtime and can generate fatal errors compared to the former type of exception.


2 Answers

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 expected
    pass
like image 92
Levi Noecker Avatar answered Sep 30 '22 12:09

Levi Noecker


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']")
if len(elem) > 0
    elem[0].click()
like image 20
JeffC Avatar answered Sep 30 '22 10:09

JeffC