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

多页面爬虫如何点击show more按钮避免元素未找到报错

解决方案

核心逻辑是先判断show more按钮是否存在,存在时才执行点击操作,共有两种稳定实现方式:

方法1:使用find_elements判断(推荐,无需异常捕获)

find_elements在找不到匹配元素时会返回空列表,不会抛出元素未找到错误,直接判断返回列表长度即可:

# 先导入所需依赖
import time
from random import randint, sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup

# 原有代码逻辑
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
for i in range(0,10):
    url = hyperlink_list[i]
    sleep(randint(10, 24))
    driver.get(url)
    time.sleep(10)
    # 新增判断show more按钮的逻辑
    show_more_btns = driver.find_elements(By.ID, "rfq-info-header-description-showmorebutton")
    if len(show_more_btns) > 0:
        show_more_btns[0].click()
        # 点击后等待内容加载完成,可根据实际情况调整等待时长
        time.sleep(2)
    # 再解析页面
    soup = BeautifulSoup(driver.page_source, 'html.parser')

方法2:使用异常捕获处理

捕获NoSuchElementException异常,找不到元素时直接跳过操作:

# 额外导入异常类
from selenium.common.exceptions import NoSuchElementException

# 循环内的判断逻辑替换为以下内容
try:
    show_more_btn = driver.find_element(By.ID, "rfq-info-header-description-showmorebutton")
    show_more_btn.click()
    time.sleep(2)
except NoSuchElementException:
    # 找不到元素直接跳过,无需额外处理
    pass

优化提示

如果按钮加载有延迟,可将固定等待替换为Selenium显式等待,提升爬取效率:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 点击逻辑替换为,最多等待3秒判断按钮是否可点击
try:
    show_more_btn = WebDriverWait(driver, 3).until(
        EC.element_to_be_clickable((By.ID, "rfq-info-header-description-showmorebutton"))
    )
    show_more_btn.click()
    time.sleep(1)
except:
    pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:06:04