python - Selenium 检查元素是否无一异常(exception)地存在

标签 python selenium selenium-webdriver automation selenium-rc

我只想检查一个元素是否存在于 for 循环中,但它只是抛出一个异常并结束代码。我该怎么做?

最佳答案

而不是 driver.find_element你应该使用 driver.find_elements方法在这里。
像这样:

if driver.find_elements_by_xpath("/div[@class='class_name']"):
    driver.find_element_by_xpath("/div[@class='class_name']").click()

或者这个:

elements = driver.find_elements_by_xpath("/div[@class='class_name']")
if elements:
    elements[0].click()

driver.find_elements将返回一个 列表 与传递的定位器匹配的网络元素。如果找到此类元素,它将返回由 Python 解释为 bool 值 True 的非空列表。而如果没有找到匹配项,它会给你一个空列表,Python 将其解释为 bool 值 False

关于python - Selenium 检查元素是否无一异常(exception)地存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70853569/

相关文章:

Python - 绘制 3 维数组

python - 使用\: LaTeX horizontal spacing 时 matplotlib 中的 ValueError

c# - 使用 selenium C# 查找和替换文本文件中的数据

python - 使用 selenium webdriver_manager 在 unix 上打开 Chrome 浏览器时出错

python - 如何使用 selenium chrome 驱动程序 Python 3 登录代理服务器并进行身份验证?

python - 具有多个值到元组的字典

python - 试图想出 python anagram 函数

java - org.openqa.selenium.InvalidElementStateException :Cannot perform native interaction: Could not load native events component

Python + Selenium : I can't get print text from div

selenium-webdriver - 如何在 Appium ( selenium Java ) 中测试 Android Toast 消息