You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Selenium高效判断元素是否存在?

高效检查Selenium元素可见性的解决方案

原方案使用is_displayed()检查元素可见性存在以下问题:

  • 无法返回“元素未找到”的结果
  • 元素不存在时会抛出NoSuchElementError,且抛出错误耗时极长

原测试代码

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]') # 该元素存在
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]') # 该元素不存在
if hidden_element.is_displayed():
    print("Element found")
else:
    print("Element not found")

元素不存在时抛出的错误

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

高效解决方案

使用find_elements()(复数形式)替代find_element(),因为find_elements()在元素不存在时会返回空列表,不会抛出错误,之后再判断元素是否存在并检查可见性。

封装后的实现代码:

from selenium import webdriver
from selenium.webdriver.common.by import By

def is_element_visible(driver, by, locator):
    elements = driver.find_elements(by, locator)
    if elements:
        return elements[0].is_displayed()
    return False

# 测试
driver = webdriver.Firefox()
driver.get('http://www.google.com')

# 检查存在的元素
if is_element_visible(driver, By.XPATH, '/html/body/div[1]/div[1]/a[2]'):
    print("Element found and visible")
else:
    print("Element not found or not visible")

# 检查不存在的元素
if is_element_visible(driver, By.XPATH, '/html/body/div[1]/div[1]/a[20]'):
    print("Element found and visible")
else:
    print("Element not found or not visible")

该方案的优势:

  • 元素不存在时直接返回False,无需捕获异常
  • 避免了find_element()抛出错误的耗时,提升执行效率

内容的提问来源于stack exchange,提问作者user15175462

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:35:21