Santhosh Santhosh - 1 year ago 69
Python Question

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 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']"}

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download