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

使用Selenium无法点击Cookie同意弹窗按钮的问题求助

解决Selenium点击Cookie同意按钮的问题

针对https://scriptblox.com/的Cookie弹窗,你之前的代码存在两个核心问题:

  • 第一种方案没意识到弹窗处于iframe内,直接定位元素自然找不到
  • 第二种方案错误地把div元素当作iframe切换,iframe的标签是<iframe>,并非div

以下是可行的代码实现:

先确保导入必要模块:

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

执行步骤代码:

driver = webdriver.Chrome()
driver.get("https://scriptblox.com/")

wait = WebDriverWait(driver, 10)
# 等待Cookie弹窗的iframe加载完成并切换进去,通过src属性关键词定位更稳定
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[src*='consent']")))

# 定位并点击"Accept All"按钮,用文本包含的方式定位比绝对xpath更可靠
accept_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Accept All')]")))
accept_btn.click()

# 若之后需要操作页面其他元素,切回主文档
driver.switch_to.default_content()

补充说明

  • 用src*='consent'定位iframe,比绝对路径xpath更能适配页面结构的小变动
  • 按钮通过文本内容定位,避免因元素层级变化导致定位失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:30:54