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

Selenium报Unable to locate element错误:如何跳过无按钮wrapper跳转下一个元素

代码修复方案

报错根因

Selenium 的 find_element_by_css_selector 接口在未匹配到对应元素时会直接抛出 NoSuchElementException,而非返回空值。你原代码中 button_check 的赋值逻辑在遇到无按钮的 wrapper 时会直接触发异常,无法执行后续的 continue 跳过逻辑。同时你将异常捕获放在了整个循环函数外层,单次异常就会终止全部遍历流程,导致程序卡住。

修复后代码

import time

def clicking_see_more(self) -> None:
    wrappers = self.find_elements_by_css_selector('div[style="text-align: start;"]')
    def button_click():
        for i, wrapper in enumerate(wrappers):
            if i % 2 == 1:
                # 查找元素改用find_elements,无匹配结果返回空列表不会抛异常
                button_list = wrapper.find_elements_by_css_selector('div[role="button"]')
                # 列表为空说明无目标按钮,直接跳过当前wrapper
                if not button_list:
                    continue
                btn = button_list[0]
                btn.click()
                time.sleep(0.5)

    button_click()

可选增强方案(保留异常捕获)

如果需要处理点击过程中可能出现的其他异常,可以将异常捕获放到循环内部,避免影响后续元素处理:

import time
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException

def clicking_see_more(self) -> None:
    wrappers = self.find_elements_by_css_selector('div[style="text-align: start;"]')
    def button_click():
        for i, wrapper in enumerate(wrappers):
            if i % 2 == 1:
                try:
                    btn = wrapper.find_element_by_css_selector('div[role="button"]')
                    btn.click()
                    time.sleep(0.5)
                except (NoSuchElementException, ElementClickInterceptedException) as e:
                    # 无按钮或点击失败时打印日志跳过
                    print(f"处理索引为{i}的wrapper失败: {e}")
                    continue

    button_click()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:24:02