Selenium Python - 处理没有这样的元素异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38022658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:14:23  来源:igfitidea点击:

Selenium Python - Handling No such element exception

pythonpython-3.xseleniumselenium-webdriver

提问by Santhosh

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.

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

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

回答by Levi Noecker

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

回答by JeffC

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_*.

您可以查看该元素是否存在,如果存在则单击它。不需要例外。注意 中的复数“s” .find_elements_*

elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
if len(elem) > 0
    elem[0].click()

回答by Corey Goldberg

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

你这样做的方式很好..你只是想捕捉错误的异常。它被命名为NoSuchElementExceptionnosuchelementexception

回答by guigasque

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

from selenium.common.exceptions import NoSuchElementException 对我来说效果很好,解决了问题

回答by AlexCharizamhard

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

为什么不简化和使用这样的逻辑?不需要例外。

if elem.is_displayed():
    elem.click()