繁体   English   中英

Selenium 检查元素是否存在无异常

[英]Selenium check if element exists without exception

我只想检查一个元素是否存在于 for 循环中,但它只是引发异常并结束代码。 我该如何 go 关于这个?

而不是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将返回与传递的定位器匹配的 web 元素列表 In case such elements found it will return non-empty list interpreted by Python as a Boolean True while if no matches found it will give you an empty list interpreted by Python as a Boolean False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM