Selenium Python-处理无此类元素异常 [英] Selenium Python - Handling No such element exception

查看:76
本文介绍了Selenium Python-处理无此类元素异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

错误-

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:{"method":"xpath","selector":".//*[@id='SORM_TB_ACTION0']"}

推荐答案

您可以查看该元素是否存在,然后单击它是否存在.无需例外.注意.find_elements_*中的复数"s".

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()

这篇关于Selenium Python-处理无此类元素异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆