Selenium Python - 处理无此元素异常

27 人关注

我在Selenium中使用Python编写自动化测试。一个元素可能存在也可能不存在。我试图用下面的代码来处理它,当元素存在时,它可以工作。但当元素不存在时,脚本就会失败,我想在元素不存在时继续下一个语句。

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

Error -

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:{"method":"xpath","selector":".//*[@id='SORM_TB_ACTION0']"}
    
python
python-3.x
selenium
selenium-webdriver
Santhosh
Santhosh
发布于 2016-06-25
5 个回答
Levi Noecker
Levi Noecker
发布于 2016-06-25
已采纳
0 人赞同

你没有导入例外吗?

from selenium.common.exceptions import NoSuchElementException
    elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
    elem.click()
except NoSuchElementException:  #spelling error making this code not work as expected
    
JeffC
JeffC
发布于 2016-06-25
0 人赞同

你可以看看这个元素是否存在,如果存在就点击它。不需要例外情况。注意 .find_elements_* 中的复数 "s"。

elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
if len(elem) > 0
    elem[0].click()
    
就性能而言,这不是更糟糕吗?我相信通过id而不是xpath来寻找一个元素要容易得多。
@SergeRogatch 100%同意,但这是OP在他们的代码中的内容,所以我复制了它。这也是4年前的事了,我想我从那时起已经学到了很多,现在除了 "只是回答问题 "之外,我更愿意提出像你这样的观点。
Corey Goldberg
Corey Goldberg
发布于 2016-06-25
0 人赞同

你的方法是正确的,只是你试图捕捉错误的异常。 它的名字是 NoSuchElementException 而不是 nosuchelementexception

DS_ShraShetty
DS_ShraShetty
发布于 2016-06-25
0 人赞同
# Handling Selenium NoSuchExpressionException
# Handling Button or element clicking common exceptions
from selenium.common.exceptions import (NoSuchElementException,ElementClickInterceptedException,ElementNotInteractableException)
   elem = driver.find_element_by_xpath(elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
       elem.click()
   except (ElementClickInterceptedException,ElementNotInteractableException):
       print("element not interactable or Click intercepted")
except NoSuchElementException:
          elem = driver.find_element_by_xpath(Alternate method)
              elem.click()
          except (ElementClickInterceptedException,ElementNotInteractableException):
              print("element not interactable or Click intercepted")
       except NoSuchElementException:
              print("Error finding element")
    
AlexCharizamhard
AlexCharizamhard
发布于 2016-06-25
0 人赞同