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

使用Selenium爬取网页时如何消除遮挡内容的「接受Cookie」弹窗

问题修复方案

你代码里的卡顿和逻辑错误由以下几个问题导致:

  • 语法层面:for循环后的所有业务代码没有正确缩进,Python不会将这部分内容识别为循环内逻辑,运行效果完全不符合预期
  • 元素定位层面:XPath中直接使用了HTML转义字符",需要替换为普通引号才能正确匹配iframe和Cookie接受按钮,否则会触发WebDriverWait超时,表现为代码长时间卡顿无响应
  • 上下文切换层面:处理完iframe内的按钮操作后,没有切回主文档上下文,后续所有主页面的元素定位都会失效
  • 容错层面:没有添加异常捕获逻辑,一旦元素加载超时就会直接抛出异常终止程序,无法保留错误信息继续执行后续任务
修复后可运行代码
from selenium import webdriver
from selenium.webdriver.opera.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time import sleep
from datetime import datetime
import pandas as pd

errors = []
season = []

# 建议把driver初始化放到循环外,复用实例提升性能
option = Options()
option.headless = False
driver = webdriver.Opera(options=option)
driver.maximize_window()

for id in range(2124889, 2124890):
    try:
        # Opening the connection and grabbing the page
        my_url = f'https://www.lefigaro.fr/sports/football/live/bundesliga/2020/{id}/*'
        driver.get(my_url)
        # 处理Cookie弹窗
        WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((
                By.XPATH,'//iframe[@id="appconsent"]')))
        WebDriverWait(driver,10).until(EC.element_to_be_clickable((
                By.XPATH,'//button[contains(@title,"Tout Accepter")]'))).click()
        # 切回主文档
        driver.switch_to.default_content()
        # 此处可添加后续页面数据抓取逻辑
    except Exception as e:
        errors.append({"id": id, "error_msg": str(e)})
        continue

# 所有任务完成后关闭driver
driver.quit()
额外优化建议
  • 不要在循环内重复初始化和销毁driver实例,复用同一个driver可以大幅提升运行效率
  • 尽量替换固定时长的sleep()调用,改用WebDriverWait判断目标元素的加载状态,减少不必要的等待时间
  • 最终可以打印errors列表查看所有抓取失败的id和对应的错误原因,方便批量排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:06:03