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

Selenium Python处理Cookie弹窗:无法定位并点击同意按钮

解决Selenium无法定位Cookie同意按钮的问题

先修正你代码里的明显错误

  • 你添加的--disable-cookies启动参数会直接阻止浏览器处理Cookie相关内容,导致Cookie弹窗加载异常或元素结构错乱,必须删除这个参数。
  • Selenium 4.1+已弃用find_element_by_xpath这类旧API,需改用find_element(By.XXX, 定位值)的写法,要先导入from selenium.webdriver.common.by import By。

修正后的可运行代码

用显式等待替代隐式等待,确保元素完全加载后再操作,避免因渲染延迟导致的定位失败:

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

s = Service(r"chromedriver.exe")
options = webdriver.ChromeOptions()

driver = webdriver.Chrome(service=s, options=options)
driver.get('https://deepai.org/machine-learning-model/fantasy-world-generator')

try:
    # 显式等待Cookie同意按钮可点击,最长等待15秒
    accept_btn = WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), "Accept")]'))
    )
    accept_btn.click()
    
    # 定位输入框并输入内容
    textarea = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, 'textarea[placeholder="Enter your prompt"]'))
    )
    textarea.send_keys('A monster')
    
    # 点击HD选项和提交按钮
    hdButton = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "modelHdButton"))
    )
    hdButton.click()
    
    submit_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "modelSubmitButton"))
    )
    submit_btn.click()
    
finally:
    driver.quit()

额外排查与备用方案

  1. 检查是否存在iframe嵌套:如果上述代码仍找不到按钮,打开F12查看Cookie弹窗元素是否在某个iframe内。若是,需先切换到iframe再定位:
    # 定位并切换到Cookie弹窗所在的iframe
    iframe = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//iframe[contains(@src, "cookie")]')))
    driver.switch_to.frame(iframe)
    # 定位并点击同意按钮
    accept_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), "Accept")]')))
    accept_btn.click()
    # 操作完成后切回主页面
    driver.switch_to.default_content()
    
  2. JavaScript强制点击:若元素存在但常规点击无效,用JS执行点击操作:
    accept_btn = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.XPATH, '//*[@id="notice"]/div[3]/div[2]/button')))
    driver.execute_script("arguments[0].click();", accept_btn)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:03:23