Selenium:使用“if"时出现错误判断一个元素是否存在 [英] Selenium: Error comes using "if" to decide whether an element exists or not

查看:56
本文介绍了Selenium:使用“if"时出现错误判断一个元素是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我问重复/愚蠢的问题,我很抱歉.我对如何确定元素是否存在感到困惑.错误:Could not locate the id smc"" 如果你运行下面的代码会弹出.

I am sorry that if I ask a duplicate/stupid questions. I am confused with how to decide if an element exists. Errors:"Could not locate the id "smc"" will pop up if you run the following code.

if driver.find_element_by_id("smc"):
    print("Yes")
else:
    print("No")

以下代码将起作用:

try:
    verification = driver.find_element_by_id("smc")
except NoSuchElementException:
    print("No exits")

在我登录页面后,它将进入以下选项之一.如果其中一个页面具有自己的元素",则要相应地进行下一步.

After I log in the page, it will enter one of the following options. Want to go the next step accordingly if one of the page has the "its own element".

1.1 page 1 
-How to verify: driver.find_element_by_id("smc")
-Next step: func1()
1.2. page 2 
-How to verify: driver.find_element_by_id("editPage")
-Next step: print("You need retry later") and exit the code
1.3. page 3
-How to verify: driver.find_element_by_id("cas2_ilecell")
-Next step: func2()

我如何完成我的任务?当我尝试使用if"但它无法工作时......

How do I complete my task? As I try to use "if" and it could not work....

非常感谢.

推荐答案

您在问题中编写了解决方案本身.如果 WebDriver 无法找到具有给定定位器的元素,并且您需要使用 try-except 处理它,则它会抛出 NoSuchElementException,如果您希望代码转到备用路径.

You wrote the solution itself in your question. WebDriver throws NoSuchElementException if it is not able to find the element with the given locator and you need to handle it using try-except if you want your code to go to to an alternate path.

如果您不想处理异常,您可以使用的其他选项是 driver.find_elements.它返回一个与定位器匹配的元素列表,如果找不到则返回一个空列表.所以你会做类似的事情 -

Other option you can use, if you don't want to handle exceptions is driver.find_elements. It returns a list of elements matching a locator and an empty list if it couldn't find any. So you will do something like -

count = len(driver.find_elements_by_id('some_id'))
if count == 0:
   //element was not found.. do something else instead

这篇关于Selenium:使用“if"时出现错误判断一个元素是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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