You need to enable JavaScript to run this app. Selenium调用无头Chrome模式时Cookie默认未启用问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Selenium调用无头Chrome模式时Cookie默认未启用问题求助

问题根因

Chrome 112版本之后,原生的--headless无头模式(旧版无头)的运行逻辑与有头模式独立,默认禁用了第三方Cookie、且部分配置项不生效,才会出现显式配置Cookie偏好仍检测失败的问题。

可行解决方案

直接将旧版无头参数替换为Chrome推出的新版无头模式参数即可,新版无头的行为与有头Chrome完全一致,Cookie默认正常启用,无需额外调整偏好配置。

  • 把参数--headless修改为--headless=new
  • (可选)Selenium 4+ 已废弃find_element_by_id写法,建议替换为find_element(By.ID, 元素id)的规范写法,避免运行报错

修改后可正常运行的代码

import selenium
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import undetected_chromedriver as uc
from fake_useragent import UserAgent

# 生成随机User Agent
ua = UserAgent()
userAgent = ua.random

# 配置Chrome参数
chrome_options = uc.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
# 替换为新版无头模式
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('window-size=1920,1080')
chrome_options.add_argument("--enable-javascript")
chrome_options.add_argument(f'user-agent={userAgent}')

# 初始化driver
driver = uc.Chrome(options=chrome_options)

# 跳转至Cookie检测页面
driver.get("https://www.whatismybrowser.com/detect/are-cookies-enabled")

# 输出Cookie是否启用,启用则打印True,否则打印False
print(driver.find_element(By.ID, "detected_value").text == "Yes")
driver.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 13:36:05