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

Selenium触发ElementClickInterceptedException报错,如何跳过异常继续点击关注按钮?

错误根因

ElementClickInterceptedException报错的核心原因是目标Follow按钮被其他元素遮挡,无法被正常点击,你的代码里存在3个直接触发该问题的逻辑缺陷:

  • 全局匹配//*[text()="Follow"]每次都默认取页面第一个Follow按钮,滚动后第一个按钮通常会被页面顶部固定导航栏遮挡,自然无法点击
  • scrollIntoView()默认将元素对齐到视口顶部,刚好会被顶部固定导航盖住,导致你定位的滚动目标按钮本身就处于被遮挡状态
  • 只捕获了NoSuchElementException异常,没有处理点击被拦截的异常,一旦触发报错就会中断后续点击流程
修复后的代码
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException

def follow():
    driver.implicitly_wait(30)  
    counter = 1  
    base_xpath = '//*[@id="react-root"]/div/section/div[3]/div/div/div[3]/div/div[3]/main/div[1]/div[2]/ul/li['

    for i in range(4, 80000, 4):
        xpath = base_xpath + str(i) + ']/button/span'
        scrollTarget = driver.find_element_by_xpath(xpath)
        # 滚动到元素对齐视口底部,避免被顶部导航遮挡
        driver.execute_script('arguments[0].scrollIntoView({block: "end"})', scrollTarget)
        print("scrolling")
        sleep(5)
        try:
            # 先批量获取当前页所有Follow按钮,避免每次找第一个
            follow_buttons = driver.find_elements_by_xpath('//*[text()="Follow"]')
            for elem in follow_buttons[:4]: # 每次取前4个点击,和你原来的逻辑对齐
                try:
                    elem.click()
                except ElementClickInterceptedException:
                    # 点击被拦截时直接用JS触发点击,绕开元素遮挡限制
                    driver.execute_script("arguments[0].click();", elem)
                counter += 1
                print(f"we followed someone {counter}")
        except NoSuchElementException:
            pass  
额外优化建议
  • 可以将固定sleep替换为WebDriverWait等待按钮可点击,减少不必要的等待时间,同时提升稳定性
  • 避免使用绝对路径XPath,页面结构一旦变动你的定位逻辑就会全部失效,建议改用属性选择器定位Follow按钮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:45:06