我只想检查一个元素是否存在于 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/