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']"}
4 个解决方案
#1
6
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_*
.
您可以查看元素是否存在,然后单击它(如果存在)。无需例外。注意.find_elements_ *中的复数“s”。
elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
if len(elem) > 0
elem[0].click()
#2
6
the way you are doing it is fine.. you are just trying to catch the wrong exception. It is named NoSuchElementException
not nosuchelementexception
你这样做的方式很好..你只是想抓住错误的例外。它被命名为NoSuchElementException而不是nosuchelementexception
#3
3
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
#4
-1
Why not simplify and use logic like this? No exceptions needed.
为什么不简化和使用这样的逻辑?无需例外。
if elem.is_displayed():
elem.click()
#1
6
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_*
.
您可以查看元素是否存在,然后单击它(如果存在)。无需例外。注意.find_elements_ *中的复数“s”。
elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
if len(elem) > 0
elem[0].click()
#2
6
the way you are doing it is fine.. you are just trying to catch the wrong exception. It is named NoSuchElementException
not nosuchelementexception
你这样做的方式很好..你只是想抓住错误的例外。它被命名为NoSuchElementException而不是nosuchelementexception
#3
3
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
#4
-1
Why not simplify and use logic like this? No exceptions needed.
为什么不简化和使用这样的逻辑?无需例外。
if elem.is_displayed():
elem.click()