feat(07-02): implement parse_json_cookies function
- Parse Chrome Cookie Editor JSON format - Filter cookies by zhihu.com domain - Handle malformed JSON with ValueError - Handle file not found with ValueError - Return cookie string in "name=value; name2=value2" format Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,51 @@
|
|||||||
|
"""Cookie 管理模块
|
||||||
|
|
||||||
|
处理 Cookie 的导入、转换和持久化。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Dict, Any
|
||||||
|
|
||||||
|
|
||||||
|
def parse_json_cookies(json_path: str) -> str:
|
||||||
|
"""从 JSON 文件解析 Cookie 为字符串格式
|
||||||
|
|
||||||
|
支持 Chrome Cookie Editor 导出的 JSON 格式:
|
||||||
|
[{"name": "z_c0", "value": "xxx", "domain": ".zhihu.com"}, ...]
|
||||||
|
|
||||||
|
Args:
|
||||||
|
json_path: JSON 文件路径
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Cookie 字符串,格式: "name1=value1; name2=value2"
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: JSON 格式无效或文件不存在
|
||||||
|
"""
|
||||||
|
path = Path(json_path)
|
||||||
|
if not path.exists():
|
||||||
|
raise ValueError(f"Cookie file not found: {json_path}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(path, 'r', encoding='utf-8') as f:
|
||||||
|
cookies = json.load(f)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
raise ValueError(f"Invalid JSON format: {e}")
|
||||||
|
|
||||||
|
if not isinstance(cookies, list):
|
||||||
|
raise ValueError("Expected JSON array")
|
||||||
|
|
||||||
|
# 过滤知乎域名,转换为 name=value 格式
|
||||||
|
zhihu_cookies = []
|
||||||
|
for c in cookies:
|
||||||
|
if not isinstance(c, dict):
|
||||||
|
continue
|
||||||
|
domain = c.get('domain', '')
|
||||||
|
if 'zhihu.com' in domain:
|
||||||
|
name = c.get('name', '')
|
||||||
|
value = c.get('value', '')
|
||||||
|
if name and value:
|
||||||
|
zhihu_cookies.append(f"{name}={value}")
|
||||||
|
|
||||||
|
return '; '.join(zhihu_cookies)
|
||||||
Reference in New Issue
Block a user