Selenium Python - Handling No such element exception

前端 未结 5 1184
暗喜
暗喜 2021-02-14 01:33

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 scr

相关标签:
5条回答
  • 2021-02-14 02:05

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

    0 讨论(0)
  • 2021-02-14 02:09

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

    if elem.is_displayed():
        elem.click()
    
    0 讨论(0)
  • 2021-02-14 02:09

    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
    
    0 讨论(0)
  • 2021-02-14 02:14

    from selenium.common.exceptions import NoSuchElementException worked pretty well to me, solved the problem

    0 讨论(0)
  • 2021-02-14 02:21

    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()
    
    0 讨论(0)
提交回复
热议问题