繁体   English   中英

使用 Python Selenium 快速检查元素是否存在

[英]Quick checking if element exists with Python Selenium

我找到了关于检查元素可见性的答案 我对这个答案的问题是,它永远不会返回“找不到元素”。 不仅。 给出错误消息需要很长时间(如下)。

from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
driver.get('http://www.google.com')


element = driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/a[2]') #this element exists
if element.is_displayed():
    print("Element found")
else:
    print("Element not found")

hidden_element = driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/a[20]') #this one doesn't exist
if hidden_element.is_displayed():
    print("Element found")
else:
    print("Element not found")

我需要更高效的东西并返回 False 或其他错误消息:

RemoteError@chrome://remote/content/shared/RemoteError.jsm:12:1 WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:192:5 NoSuchElementError@chrome://remote/content/ shared/webdriver/Errors.jsm:404:5 element.find/</<@chrome://remote/content/marionette/element.js:291:16

您可以使用driver.find_elements方法代替driver.find_element
像这样的东西:

if driver.find_elements(By.XPATH,'/html/body/div[1]/div[1]/a[20]'):
    print("Element found")
else:
    print("Element not found")

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 .
为了减少这里花费的时间,您可以将implicitly_wait定义为一些短值,例如 1 或 2 秒,如下所示:

driver.implicitly_wait(2)

UPD
如果您想检查元素显示状态,您可以按索引从列表中获取元素,如下所示:

elements = driver.find_elements(By.XPATH,'/html/body/div[1]/div[1]/a[20]')
if elements:
    print("Element found")
    if elements[0].is_displayed():
        print("Element is also displayed")
else:
    print("Element not found")

您可以检查元素的长度

hidden_element = driver.find_elements(By.XPATH,'/html/body/div[1]/div[1]/a[20]') #this one doesn't exist
if len(hidden_element)>0:
    print("Element found")
else:
    print("Element not found"

)

暂无
暂无

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

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