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

如何解决Python无法打开谷歌Chrome浏览器Cookies文件的问题?

解决Chrome浏览器Cookies文件读取问题

Chrome的Cookies文件本质是SQLite数据库,但默认被加密,这就是你直接用SQLite打不开的核心原因。以下是具体解决思路和实现步骤:

关键背景

Chrome会对本地存储的Cookies、历史记录等SQLite数据加密,加密密钥的存储位置因系统而异:

  • Windows:密钥存放在%LOCALAPPDATA%\Google\Chrome\User Data\Local State(JSON格式文件),需提取os_crypt下的encrypted_key,再用系统DPAPI解密。
  • macOS:密钥保存在系统钥匙串,标签为Chrome Safe Storage,需通过钥匙串服务获取并解密。
  • Linux:密钥同样在~/.config/google-chrome/Local State的JSON中,用用户登录密码解密。

Python读取实现(以Windows为例)

1. 获取解密密钥

import json
import win32crypt

def get_chrome_decrypt_key():
    local_state_path = r"C:\Users\<你的用户名>\AppData\Local\Google\Chrome\User Data\Local State"
    with open(local_state_path, "r", encoding="utf-8") as f:
        local_state = json.load(f)
    # 提取加密密钥,去掉DPAPI前缀后解密
    encrypted_key = local_state["os_crypt"]["encrypted_key"]
    raw_key = bytes.fromhex(encrypted_key[5:])
    decrypt_key = win32crypt.CryptUnprotectData(raw_key, None, None, None, 0)[1]
    return decrypt_key

2. 解密并读取Cookies数据

import sqlite3
import shutil
import os
from Crypto.Cipher import AES

def decrypt_cookie_value(encrypted_val, key):
    # Chrome的加密格式为v10开头的AES-GCM
    if encrypted_val.startswith(b"v10"):
        nonce = encrypted_val[3:15]
        ciphertext = encrypted_val[15:-16]
        tag = encrypted_val[-16:]
        cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
        return cipher.decrypt_and_verify(ciphertext, tag).decode("utf-8")
    return ""

def read_chrome_cookies():
    key = get_chrome_decrypt_key()
    cookies_path = r"C:\Users\<你的用户名>\AppData\Local\Google\Chrome\User Data\Default\Cookies"
    # Chrome运行时会锁定数据库,先复制临时文件
    temp_db = "temp_chrome_cookies.db"
    shutil.copy(cookies_path, temp_db)

    conn = sqlite3.connect(temp_db)
    cursor = conn.cursor()
    cursor.execute("SELECT name, value, encrypted_value, domain FROM cookies")
    
    cookie_list = []
    for row in cursor.fetchall():
        name, plain_val, encrypted_val, domain = row
        # 优先使用解密后的值
        if not plain_val and encrypted_val:
            plain_val = decrypt_cookie_value(encrypted_val, key)
        cookie_list.append({
            "name": name,
            "value": plain_val,
            "domain": domain
        })
    
    conn.close()
    os.remove(temp_db)
    return cookie_list

3. 注意事项

  • 必须关闭Chrome再操作,否则数据库文件会被进程锁定,无法复制。
  • 需要提前安装依赖:pip install pywin32 pycryptodome。
  • macOS/Linux版本需调整密钥获取逻辑,比如macOS用keyring库读取钥匙串,Linux用cryptography处理密码解密。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:40:38