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

Chrome Driver无法获取Cookie?使用Selenium获取谷歌Cookie求助

解决Selenium获取谷歌账户Cookie的问题

看你的代码里有几个关键问题,我一步步帮你梳理修正:

1. 核心错误:Cookie获取时机+等待逻辑问题

你的代码在登录循环后直接执行driver.quit(),之后才想获取Cookie——这时候浏览器已经关闭,根本拿不到任何Cookie!而且那个while循环是忙等待,会持续占用CPU,完全没必要,应该用Selenium的显式等待来替代。

2. 谷歌的反自动化检测

谷歌对Selenium默认的特征很敏感,直接用默认配置大概率会被检测到,导致登录异常或者Cookie获取不全,需要给ChromeDriver加一些规避配置。

修正后的完整代码

import json
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

taskID = input("Choose task: ")

# 配置ChromeOptions规避谷歌自动化检测
chrome_options = Options()
# 禁用自动化扩展提示
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
# 关闭自动化扩展
chrome_options.add_experimental_option('useAutomationExtension', False)
# 关键:禁用Chrome的自动化控制提示
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
# 可选:复用本地已登录的Chrome会话,避免重复手动登录
# chrome_options.add_argument(r"user-data-dir=C:\Users\你的用户名\AppData\Local\Google\Chrome\User Data")

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://accounts.google.com/ServiceLogin?service=accountsettings&passive=1209600&osid=1&continue=https://myaccount.google.com/intro&followup=https://myaccount.google.com/intro")

# 显式等待登录完成:等待URL跳转到谷歌账户页面,超时时间设为60秒(足够手动完成登录)
try:
    WebDriverWait(driver, 60).until(
        EC.url_contains("myaccount.google.com")
    )
    print("登录成功!")
    
    # 登录后立即获取Cookie
    gcooks = driver.get_cookies()
    
    # 把Cookie转成键值对格式,方便后续接口请求使用
    cookie_dict = {cookie['name']: cookie['value'] for cookie in gcooks}
    
    # 保存Cookie到本地文件
    with open("google_cookies.json", "w") as f:
        json.dump(gcooks, f, indent=4)
    print("Cookie已保存到google_cookies.json")
    
finally:
    # 所有操作完成后再关闭浏览器
    driver.quit()

额外注意事项

  • 超时时间调整:如果你的登录操作需要更长时间,把WebDriverWait的超时参数调大(比如120秒)。
  • 用户数据目录:配置user-data-dir后,Selenium会复用你本地Chrome的登录会话,不用每次手动输入账号密码,但注意不要同时打开本地Chrome和Selenium的Chrome实例。
  • Cookie有效期:谷歌的敏感Cookie(如SID)有有效期,过一段时间会失效,需要重新获取。
  • 进阶规避检测:如果还是被谷歌检测到,可以尝试使用undetected-chromedriver库(专门针对谷歌反爬优化的Selenium分支)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:29:51