pythonselenium-webdriverwebdrivertry-exceptnosuchelementexception

How to use try-except to skip the case that selenium is unable to locate element using Selenium and Python


My question is how to use try-expect to skip the case that selenium is unable to locate element. For some reasons, I have to skip the situation described above.I want to use try-expect, but I don’t know what to write after except.

I use Python version 3.8.6, chromeriver version 87.0.4280.88, and selenium version number 3.141.0,window 10

for example():

driver = webdriver.Chrome()
driver.get("https:www.google.com")
try:
    driver.find_element_by_xpath('//*[@id="cdNav"]/ul/li[5]/ul/li[1]/a').click()
except:
    pass

The current error occurred:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[3]/div/nav/ul/li[5]/a"}
  (Session info: chrome=87.0.4280.88)

Normally,I could write IndentationError, SyntaxError and so on, but I dont 't know what type of error to write after EXPECT in above case.

This problem has troubled me for a long time, I hope it can be solved, thank you very much


Solution

  • find_element_by_xpath()

    find_element_by_xpath() returns NoSuchElementException if the element wasn't found.

    So ideally you need to catch NoSuchElementException and your effective code block will be:

    driver = webdriver.Chrome()
    driver.get("https:www.google.com")
    try:
        driver.find_element_by_xpath('//*[@id="cdNav"]/ul/li[5]/ul/li[1]/a').click()
    except nosuchelementexception:
        pass
    

    Note: You have to add the following imports:

    from selenium.common.exceptions import NoSuchElementException