Windows下Python实现Chrome运行时获取Cookie的可行方案
方案1:利用Chrome远程调试协议(CDP)
Chrome自带远程调试能力,无需额外安装驱动,适配所有Chrome版本,适合分发场景:
- 启动Chrome时添加参数:
chrome.exe --remote-debugging-port=9222(可封装成批处理脚本让用户一键启动) - 通过Python连接调试端口,调用CDP接口获取Cookie:
import requests import json import websockets import asyncio async def fetch_chrome_cookies(): # 获取调试目标列表 targets = requests.get('http://localhost:9222/json').json() # 筛选出页面类型的调试地址 debug_ws_url = next(t['webSocketDebuggerUrl'] for t in targets if t['type'] == 'page') async with websockets.connect(debug_ws_url) as ws: # 发送获取Cookie的CDP命令 await ws.send(json.dumps({ "id": 1, "method": "Network.getCookies" })) response = await ws.recv() result = json.loads(response) return result['result']['cookies'] # 执行并打印结果 cookies = asyncio.run(fetch_chrome_cookies()) print(cookies)
- 核心优势:和Chrome版本完全同步,无需单独维护驱动,分发成本低
- 注意:必须确保Chrome以远程调试模式启动,否则无法连接
方案2:复制Cookie数据库副本读取
Chrome运行时会锁定原始Cookie文件,但可以先复制副本再读取,避开文件锁:
import shutil import sqlite3 import os import win32crypt from datetime import datetime # Chrome Cookie文件路径 cookie_source = os.path.expandvars(r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\Cookies') # 临时副本路径 temp_cookie_db = os.path.join(os.getenv('TEMP'), 'chrome_cookies_temp.db') # 复制Cookie文件到临时目录 shutil.copy2(cookie_source, temp_cookie_db) # 读取并解密Cookie conn = sqlite3.connect(temp_cookie_db) cursor = conn.cursor() cursor.execute("SELECT name, value, domain, path, expires_utc FROM cookies") for row in cursor.fetchall(): name, encrypted_val, domain, path, expires = row # 解密新版Chrome的Cookie值(Windows DPAPI加密) decrypted_val = win32crypt.CryptUnprotectData(encrypted_val, None, None, None, 0)[1].decode('utf-8') # 转换过期时间格式 expires_time = datetime.utcfromtimestamp((expires - 11644473600000000) / 1000000) print(f"{name}={decrypted_val}; Domain={domain}; Path={path}; Expires={expires_time}") # 清理临时文件 conn.close() os.remove(temp_cookie_db)
- 注意:需要安装
pywin32库(pip install pywin32)处理DPAPI解密 - 局限性:若Chrome正在写入Cookie,副本可能存在数据不一致情况
方案3:通过Chrome扩展获取Cookie
开发轻量Chrome扩展,直接调用Chrome原生API获取Cookie,完全避开文件锁问题:
- 扩展
manifest.json(v3版本):
{ "manifest_version": 3, "name": "Cookie Exporter", "version": "1.0", "permissions": ["cookies", "<all_urls>"], "background": { "service_worker": "background.js" } }
- 扩展
background.js:
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/get-cookies') { chrome.cookies.getAll({}, (cookies) => { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(cookies)); }); } }); server.listen(8080);
- Python脚本调用扩展接口:
import requests cookies = requests.get('http://localhost:8080/get-cookies').json() print(cookies)
- 优势:兼容性拉满,不受Chrome版本和文件锁限制
- 注意:需要引导用户安装扩展,可打包成CRX文件分发
内容的提问来源于stack exchange,提问作者Robin Škába
相关产品推荐
相关产品推荐

