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

Selenium爬虫开发:能否用if/else判断元素是否存在?

Selenium元素判断问题解答

你写的逻辑没法直接实现,因为Selenium的driver.find_element()方法找不到目标元素时,不会返回False或空值,而是直接抛出NoSuchElementException异常,代码会直接中断,根本走不到后面的判断步骤。

给你两种可行的实现方式:

方式一:用复数形式的find_elements()(更简洁)

find_elements()找不到元素时会返回空列表,而非抛出异常,这样就能直接做存在性判断:

from selenium.webdriver.common.by import By

# 获取所有匹配指定类名的元素,返回列表
restaurant_elements = driver.find_elements(By.CLASS_NAME, "_2YIdLB")
# 列表非空则说明找到元素,取第一个的文本内容
if restaurant_elements:
    print(restaurant_elements[0].text)
else:
    pass

方式二:捕获异常(更灵活)

如果一定要用find_element(),就需要主动捕获它抛出的异常:

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

try:
    restaurant_description = driver.find_element(By.CLASS_NAME, "_2YIdLB").text
    print(restaurant_description)
except NoSuchElementException:
    # 找不到元素时直接跳过
    pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:20:43