Files
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

591 lines
21 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
平台用量抓取服务(Playwright 自动化)
====================================
【功能说明】
用 Playwright 内置浏览器打开平台控制台,登录后保存 Cookie,
之后用 Cookie 自动抓取用量数据(多账号多套餐并行)。
【技术选型理由】
1. Playwright:能渲染 JS SPA(小米/火山控制台都是 React/Vue);
2. Cookie 持久化:登录一次,之后自动复用;
3. 无头模式:正式抓取用 headless,登录时用有头模式。
【实现思路】
- login_and_save_cookies():打开浏览器让你登录,登录后保存 Cookie;
- scrape_usage():用 Cookie 后台抓取用量页面并解析;
- 多账号串行执行(避免并发浏览器吃内存)。
【潜在风险与应对】
风险1:平台改版导致 CSS 选择器失效。
应对:解析失败时截图保存 + 返回页面文本供人工分析;
风险2:Cookie 过期。
应对:抓取时检测登录态,失效则提示重新登录;
风险3:页面加载慢。
应对:等待 networkidle + 显式等待关键元素,超时 30s。
"""
from __future__ import annotations
import base64
import json
import logging
import os
from datetime import datetime
from pathlib import Path
logger = logging.getLogger("agent.platform_scraper")
# 浏览器内核路径(已下载到 D 盘)
BROWSERS_PATH = Path(r"D:\Agent\agent\data\pw-browsers")
SCREENSHOT_DIR = Path(r"D:\Agent\agent\data\platform_screenshots")
def _ensure_browsers_env() -> None:
"""确保 Playwright 浏览器路径指向 D 盘。"""
os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", str(BROWSERS_PATH))
# ========== 登录会话管理(两步式:打开浏览器 → 用户点完成 → 保存)==========
# 登录会话:account_id → {playwright, browser, context, page, initial_url, started_at}
_login_sessions: dict[str, dict[str, Any]] = {}
def start_login(account_id: str, console_url: str) -> dict:
"""
第一步:打开浏览器(保持存活,等用户点「登录完成」)。
【改进】不再等待超时,浏览器一直开着,直到 finish_login 被调用。
"""
_ensure_browsers_env()
from playwright.sync_api import sync_playwright
# 如果该账号已有活跃会话,先关闭
if account_id in _login_sessions:
finish_login(account_id, save=False)
try:
pw = sync_playwright().start()
browser = pw.chromium.launch(headless=False)
context = browser.new_context(
viewport={"width": 1400, "height": 900},
locale="zh-CN",
)
page = context.new_page()
page.goto(console_url, timeout=30000)
_login_sessions[account_id] = {
"pw": pw,
"browser": browser,
"context": context,
"page": page,
"initial_url": page.url,
"started_at": datetime.now().astimezone().isoformat(),
}
logger.info("登录浏览器已打开(account=%s),等待用户完成登录", account_id)
return {
"success": True,
"message": "浏览器已打开,请在浏览器中完成登录,完成后点击「登录完成」",
}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": f"打开浏览器失败:{exc}"}
def finish_login(account_id: str, save: bool = True) -> dict:
"""
第二步:保存 Cookie + localStorage,关闭浏览器。
【参数】save=True 正常保存;False 表示取消登录(不保存)。
"""
session = _login_sessions.pop(account_id, None)
if session is None:
return {"success": False, "message": "没有进行中的登录会话"}
cookies: list = []
local_storage: dict = {}
try:
cookies = session["context"].cookies()
except Exception: # noqa: BLE001
cookies = []
try:
raw = session["page"].evaluate("() => JSON.stringify(localStorage)")
local_storage = json.loads(raw) if raw else {}
except Exception: # noqa: BLE001
pass
# 关闭浏览器
try:
session["browser"].close()
except Exception: # noqa: BLE001
pass
try:
session["pw"].stop()
except Exception: # noqa: BLE001
pass
if not save:
return {"success": True, "message": "登录会话已取消"}
if not cookies and not local_storage:
return {
"success": False,
"message": "未获取到登录态,请确认已在浏览器中完成登录",
}
# 保存到数据库
from app.store.platform_account_store import get_platform_store
store = get_platform_store()
session_data = {"cookies": cookies, "local_storage": local_storage}
store.save_cookies(account_id, json.dumps(session_data, ensure_ascii=False))
logger.info(
"登录态已保存(account=%s,Cookie %d 个 + localStorage %d 项)",
account_id,
len(cookies),
len(local_storage),
)
return {
"success": True,
"message": f"登录态已保存(Cookie {len(cookies)} 个)",
"cookie_count": len(cookies),
"local_storage_count": len(local_storage),
}
def login_and_save_cookies(
console_url: str,
account_id: str,
timeout_seconds: int = 180,
) -> dict:
"""
兼容旧接口:一步式登录(内部调用两步式)。
"""
start_result = start_login(account_id, console_url)
if not start_result.get("success"):
return start_result
# 等待一段时间后自动保存(兼容旧调用方)
import time
time.sleep(min(timeout_seconds, 30))
return finish_login(account_id)
def scrape_usage(account_id: str, timeout_seconds: int = 30) -> dict:
"""
用已保存的 Cookie 后台抓取用量数据。
【策略】
1. 加载 Cookie → 打开控制台 URL;
2. 等待页面渲染完成(含 JS 动态内容)→ 截图保存;
3. 多策略提取页面文本 → 解析用量数据;
4. 保存用量快照 + 原始文本(供调试)。
"""
_ensure_browsers_env()
from playwright.sync_api import sync_playwright
from app.store.platform_account_store import get_platform_store
store = get_platform_store()
account = store.get_with_cookies(account_id)
if not account:
return {"success": False, "message": f"账号不存在:{account_id}"}
if not account.get("cookies"):
return {
"success": False,
"message": "该账号尚未登录,请先执行「登录」保存 Cookie",
}
try:
session = json.loads(account["cookies"])
# 兼容旧格式(纯 Cookie 数组)与新格式({cookies, local_storage})
if isinstance(session, list):
cookies = session
local_storage = {}
else:
cookies = session.get("cookies", [])
local_storage = session.get("local_storage", {})
except json.JSONDecodeError:
return {"success": False, "message": "Cookie 格式损坏,请重新登录"}
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
screenshot_path = SCREENSHOT_DIR / f"{account['brand']}_{account['account_name']}_{ts}.png"
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context(
viewport={"width": 1400, "height": 900},
locale="zh-CN",
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
)
context.add_cookies(cookies)
page = context.new_page()
# 恢复 localStorage(有些站点用 token 存在这里)
if local_storage:
try:
import json as _json
storage_script = (
"localStorage.clear();"
+ "".join(
f"localStorage.setItem({json.dumps(k)}, {json.dumps(v)});"
for k, v in local_storage.items()
)
)
page.add_init_script(storage_script)
except Exception: # noqa: BLE001
pass
try:
page.goto(account["console_url"], timeout=30000)
# 关键改进:等待 JS 渲染完成(SPA 需要额外时间)
try:
page.wait_for_load_state("networkidle", timeout=timeout_seconds * 1000)
except Exception: # noqa: BLE001
pass
# 额外等待 3 秒让动态内容渲染
page.wait_for_timeout(3000)
# 尝试等待页面出现文本内容
try:
page.wait_for_function(
"document.body.innerText.length > 100",
timeout=10000,
)
except Exception: # noqa: BLE001
pass
# 截图
page.screenshot(path=str(screenshot_path), full_page=True)
# 多策略提取文本
page_text = ""
try:
page_text = page.inner_text("body")
except Exception: # noqa: BLE001
pass
if not page_text or len(page_text) < 50:
# 降级:从 HTML 提取
try:
html = page.content()
import re as _re
clean = _re.sub(r"<(script|style)[^>]*>.*?</\1>", "", html, flags=_re.DOTALL)
clean = _re.sub(r"<[^>]+>", " ", clean)
page_text = _re.sub(r"\s+", " ", clean)
except Exception: # noqa: BLE001
pass
# 保存原始文本(供调试)
text_path = SCREENSHOT_DIR / f"{account['brand']}_{account['account_name']}_{ts}.txt"
try:
text_path.write_text(page_text[:20000], encoding="utf-8")
except Exception: # noqa: BLE001
pass
browser.close()
# 关键改进:检测是否在登录页(Cookie 失效)
login_keywords = ["登录", "注册", "忘记密码", "立即登录", "请登录", "未登录", "Login"]
is_login_page = any(kw in page_text[:500] for kw in login_keywords)
if is_login_page and not any(
kw in page_text for kw in ["退出登录", "个人中心", "用户中心"]
):
# 记录登录过期(供前端右上角提示)
_record_login_expired(
account_id,
account.get("brand", ""),
account.get("account_name", ""),
)
return {
"success": False,
"message": "Cookie 已过期或未登录,请重新执行「登录」",
"screenshot": str(screenshot_path),
"page_text_preview": page_text[:300],
}
# 解析用量数据
usage_data = _parse_usage_text(page_text, account["brand"])
usage_data["raw_text_preview"] = page_text[:300]
# 保存快照
snapshot = store.save_snapshot(account_id, usage_data)
return {
"success": True,
"message": f"抓取完成({account['brand']}-{account['account_name']})",
"usage": usage_data,
"screenshot": str(screenshot_path),
"snapshot_id": snapshot["id"],
"page_text_length": len(page_text),
"page_text_preview": page_text[:500],
}
except Exception as exc: # noqa: BLE001
try:
browser.close()
except Exception: # noqa: BLE001
pass
return {"success": False, "message": f"抓取失败:{exc}"}
def _parse_usage_text(text: str, brand: str) -> dict:
"""
从页面文本中解析用量数据(按指标名精确提取)。
【火山引擎式布局】指标名 → 重置信息 → 数值独占一行 → % → 坐标轴标签
【小米式布局】直接用文字描述(如「已用 45%」)
【提取指标】
- 剩余时间(如「25天」)
- 近5小时用量
- 近一周用量
- 近一月用量
"""
import re
usage_percent = 0.0
used_amount = ""
total_amount = ""
remain_amount = ""
expire_date = ""
usage_5h = ""
usage_1w = ""
usage_1m = ""
lines = text.splitlines()
lines_stripped = [l.strip() for l in lines]
def _find_value_after_label(label: str, max_lookahead: int = 6) -> str:
"""
在文本行中找标签,然后往后扫描找数值(跳过「重置」等中间行)。
【布局】标签 → [重置信息] → 数值 → % → 坐标轴标签
"""
for i, line in enumerate(lines_stripped):
if label in line:
for j in range(i + 1, min(i + max_lookahead, len(lines_stripped))):
candidate = lines_stripped[j]
if not candidate:
continue
if any(kw in candidate for kw in ["重置", "即将", "后重置"]):
continue
if candidate == "%":
continue
if candidate in ("0%", "50%", "100%"):
continue
if re.match(r"^[\d,\.]+\s*(%|天|日|月|小时|个)?$", candidate):
return candidate
if re.match(r"^[\d,\.]+", candidate):
return candidate
return ""
def _find_reset_after_label(label: str, max_lookahead: int = 6) -> str:
"""
找标签后的「重置时间」信息(如「即将重置」「5天9小时后重置」)。
"""
for i, line in enumerate(lines_stripped):
if label in line:
for j in range(i + 1, min(i + max_lookahead, len(lines_stripped))):
candidate = lines_stripped[j]
if not candidate:
continue
# 匹配重置时间模式
if "重置" in candidate:
return candidate
return ""
# 提取「剩余时间」
remain_time = _find_value_after_label("剩余时间")
if remain_time:
remain_amount = remain_time
# 提取「近5小时用量」及其重置时间
usage_5h = _find_value_after_label("近5小时用量")
reset_5h = _find_reset_after_label("近5小时用量")
# 提取「近一周用量」及其重置时间
usage_1w = _find_value_after_label("近一周用量")
reset_1w = _find_reset_after_label("近一周用量")
# 提取「近一月用量」及其重置时间
usage_1m = _find_value_after_label("近一月用量")
reset_1m = _find_reset_after_label("近一月用量")
# 主用量百分比:优先取近一月 > 近一周 > 近5小时
for val in [usage_1m, usage_1w, usage_5h]:
m = re.match(r"([\d\.]+)", val or "")
if m:
usage_percent = float(m.group(1))
break
# 通用模式补充(兼容小米等其他平台)
if not any([usage_5h, usage_1w, usage_1m]):
# 小米式:「已用 45%」
pct_with_label = re.search(
r"(?:已用|使用|已消耗|用量|used)[^%\n]{0,20}?(\d+(?:\.\d+)?)\s*%", text, re.IGNORECASE
)
if pct_with_label:
usage_percent = float(pct_with_label.group(1))
else:
pct_matches = re.findall(r"(\d+(?:\.\d+)?)\s*%", text)
real_pcts = [float(p) for p in pct_matches if float(p) not in (0, 50, 100)]
if real_pcts:
usage_percent = real_pcts[0]
# 小米式:「当前套餐用量」后的「X / Y」分数(已用/总量)
xiaomi_fraction = re.search(
r"当前套餐用量\s*\n\s*([\d,]+)\s*/\s*([\d,]+)", text
)
if xiaomi_fraction:
used_amount = xiaomi_fraction.group(1).strip()
total_amount = xiaomi_fraction.group(2).strip()
# 计算剩余
try:
used_val = int(used_amount.replace(",", ""))
total_val = int(total_amount.replace(",", ""))
remain_val = total_val - used_val
remain_amount = f"{remain_val:,}"
except ValueError:
pass
# 小米式:「Token 总消耗」后的数量
if not used_amount:
token_total = re.search(
r"Token\s*总消耗\s*\n\s*([\d,]+)\s*(?:Tokens?)?", text
)
if token_total:
used_amount = token_total.group(1).strip() + " Tokens"
# 分数形式(通用)
if not used_amount:
fraction = re.search(r"([\d,\.]+)\s*/\s*([\d,\.]+)", text)
if fraction:
used_amount = fraction.group(1)
total_amount = fraction.group(2)
# Token 数量(通用)
if not used_amount:
token_match = re.search(r"([\d,\.]+)\s*(?:tokens?|tok)", text, re.IGNORECASE)
if token_match:
used_amount = token_match.group(1)
# 小米式:「有效期至」日期(如「有效期至 2026-11-13 23:59:59 (UTC)」)
valid_until_match = re.search(r"有效期至\s*(\d{4}-\d{2}-\d{2})", text)
valid_until = valid_until_match.group(1) if valid_until_match else ""
# 到期日期(优先取「结束时间」后的日期)
expire_match = re.search(
r"(?:结束时间|到期|截止|expire|end)[:\s]*(\d{4}-\d{2}-\d{2})", text, re.IGNORECASE
)
if expire_match:
expire_date = expire_match.group(1)
elif valid_until:
expire_date = valid_until
else:
all_dates = re.findall(r"(\d{4}-\d{2}-\d{2})", text)
if all_dates:
expire_date = all_dates[-1]
return {
"usage_percent": usage_percent,
"used_amount": used_amount,
"total_amount": total_amount,
"remain_amount": remain_amount,
"expire_date": expire_date,
"valid_until": valid_until,
"usage_5h": usage_5h,
"usage_1w": usage_1w,
"usage_1m": usage_1m,
"reset_5h": reset_5h,
"reset_1w": reset_1w,
"reset_1m": reset_1m,
"brand": brand,
"raw_data": {
"text_length": len(text),
"text_preview": text[:500],
},
}
# ========== 抓取进度追踪 ==========
# 全局进度:{running, total, completed, current_account, results, started_at}
_scrape_progress: dict[str, Any] = {
"running": False,
"total": 0,
"completed": 0,
"current_account": "",
"results": [],
"started_at": "",
}
# 登录过期追踪:account_id → {brand, account_name, detected_at}
_login_expired: dict[str, dict[str, Any]] = {}
def get_scrape_progress() -> dict:
"""获取当前抓取进度(供前端轮询)。"""
return dict(_scrape_progress)
def get_login_expired() -> list[dict]:
"""获取登录过期的账号列表(供前端右上角提示)。"""
return [
{"account_id": aid, **info} for aid, info in _login_expired.items()
]
def clear_login_expired(account_id: str) -> None:
"""清除某账号的登录过期标记(重新登录后调用)。"""
_login_expired.pop(account_id, None)
def _record_login_expired(account_id: str, brand: str, account_name: str) -> None:
"""记录登录过期。"""
from datetime import datetime
_login_expired[account_id] = {
"brand": brand,
"account_name": account_name,
"detected_at": datetime.now().astimezone().isoformat(timespec="seconds"),
}
logger.warning("检测到登录过期:%s-%s", brand, account_name)
def scrape_all_accounts() -> list[dict]:
"""抓取所有已激活账号的用量(串行执行,带进度追踪)。"""
from app.store.platform_account_store import get_platform_store
store = get_platform_store()
accounts = [a for a in store.list_all() if a.get("is_active")]
total = len(accounts)
# 重置进度
_scrape_progress.update({
"running": True,
"total": total,
"completed": 0,
"current_account": "",
"results": [],
"started_at": datetime.now().astimezone().isoformat(),
})
results = []
try:
for account in accounts:
_scrape_progress["current_account"] = f"{account['brand']}-{account['account_name']}"
result = scrape_usage(account["id"])
results.append({"account_id": account["id"], "brand": account["brand"], **result})
_scrape_progress["results"] = list(results)
_scrape_progress["completed"] = len(results)
finally:
_scrape_progress["running"] = False
return results