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

如何使用Python Selenium点击Cookiebot uc.js生成的Cookie同意按钮

用Python Selenium点击Cookiebot生成的Cookie同意按钮方案

Cookiebot注入的同意弹窗默认有固定的元素ID、类名和属性标识,直接通过显式等待匹配对应元素即可完成点击,无需额外解析引入的uc.js逻辑。

完整实现代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化Chrome驱动,可根据需要替换为其他浏览器驱动
driver = webdriver.Chrome()
# 替换为你的目标页面地址
driver.get("https://example.com")

try:
    # 优先匹配默认的同意全部按钮ID,这是Cookiebot的标准默认ID
    allow_all_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll"))
    )
    allow_all_btn.click()
except:
    # 第一种ID匹配失败时,尝试备选选择器
    try:
        # 备选1:匹配同意全部按钮的标准类名
        allow_all_btn = WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "CybotCookiebotDialogBodyButtonAllowAll"))
        )
        allow_all_btn.click()
    except:
        # 备选2:通过自定义属性匹配
        allow_all_btn = WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-cy='allow-all']"))
        )
        allow_all_btn.click()

兼容调整说明

  • 若站点自定义了Cookiebot按钮文本,可通过XPATH匹配文本内容,比如中文站点可以用By.XPATH, "//button[contains(text(), '同意全部')]"作为定位条件
  • 部分站点会将Cookiebot弹窗放在独立iframe中,找不到元素时可以先检查是否存在ID为CookiebotIframe的iframe,切换进入iframe后再执行元素匹配
  • 动态渲染的弹窗不建议用隐式等待,使用显式等待的稳定性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:54:07