- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
960 lines
37 KiB
Python
960 lines
37 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""浏览器抓包工具(DrissionPage 版)。
|
||
|
||
打开一个可交互的 Chromium 内核浏览器(Chrome / Edge),通过 DrissionPage 的
|
||
监听器(CDP Network 域)记录【所有标签页】的全部网络请求,实时落盘,退出时
|
||
汇总为 HAR / JSONL / CSV,便于在 DevTools、Postman 或代码里复用接口。
|
||
|
||
特性:
|
||
* 手动操作浏览器即可抓包(登录、点按、跳转都算),不限制单页;
|
||
* 默认捕获全部方法(含 PUT/DELETE/PATCH/OPTIONS),默认捕获全部资源类型
|
||
(Document / XHR / Fetch / Script / Image / Font / Media / WebSocket 等);
|
||
* 记录请求头、响应头、POST 数据、状态码、MIME、资源类型、耗时、远端 IP;
|
||
* 默认把文本类响应体(json/text/xml/js/css)落到 bodies/ 目录,HAR 内联;
|
||
* 输出可直接拖进 Chrome DevTools「Network → Import HAR」回放查看;
|
||
* 支持连接已开调试端口的浏览器(--attach-port),不动用户现有窗口。
|
||
|
||
用法::
|
||
|
||
# 最常用:打开浏览器,手动操作,Ctrl+C 或直接关掉浏览器结束
|
||
.venv\\Scripts\\python.exe tools\\net_capture.py --url https://example.com
|
||
|
||
# 指定 Edge、只抓接口类请求、不落响应体
|
||
.venv\\Scripts\\python.exe tools\\net_capture.py --browser edge ^
|
||
--target /api/ --res-type XHR Fetch --no-bodies
|
||
|
||
# 无头跑 30 秒自动结束(适合脚本化采集)
|
||
.venv\\Scripts\\python.exe tools\\net_capture.py --headless --url https://example.com ^
|
||
--duration 30
|
||
|
||
# 连接已有调试浏览器(先自行启动,注意带 --remote-allow-origins=*)
|
||
# msedge.exe --remote-debugging-port=9222 --remote-allow-origins=* --user-data-dir=D:\\tmp\\edge
|
||
.venv\\Scripts\\python.exe tools\\net_capture.py --attach-port 9222
|
||
|
||
输出目录默认 ``<仓库根>/out/netcap/<时间戳>/``:
|
||
capture.jsonl 每行一条请求(流式写入,进程被杀也不丢已抓数据)
|
||
netcap.har HAR 1.2,可导入 DevTools
|
||
requests.csv Excel 友好的请求清单
|
||
bodies/ 响应体(文本类;--all-bodies 时含二进制)
|
||
meta.json 本次运行参数与统计
|
||
|
||
已知边界:DrissionPage 监听器按标签页 attach(每 0.1 秒发现新标签页并挂监听),
|
||
* 页面内 Service Worker 发起的请求可能抓不到;
|
||
* 新标签页/新窗口里「刚打开瞬间」的文档请求可能漏抓,活跃页面的接口不受影响;
|
||
* 浏览器插件、其他进程的流量不抓。
|
||
|
||
已知坑:attach 到「无头」浏览器时,DrissionPage 会因无头标记不一致而先杀掉
|
||
浏览器再自己重启;本工具已自动探测无头状态并预置标记,不会误杀已有窗口。
|
||
|
||
测试记录(2026-11,Edge + DrissionPage 4.1.1.4):
|
||
静态页 + fetch(POST JSON) 场景,Document/Stylesheet/Script/Fetch 类型、
|
||
请求/响应头、POST 体、响应体、状态码、CDP 阶段耗时均正确入库;
|
||
--attach-port 连无头 Edge 正常,浏览器未被关闭。
|
||
|
||
退出码:0=正常结束 / 2=参数或环境错误 / 3=运行期错误 / 4=浏览器启动失败
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import base64
|
||
import csv
|
||
import json
|
||
import os
|
||
import re
|
||
import socket
|
||
import sys
|
||
import time
|
||
from collections import Counter
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Any, Dict, List, Optional, Tuple
|
||
from urllib.parse import parse_qsl, urlparse
|
||
|
||
TOOL_VERSION = "1.0.0"
|
||
|
||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||
|
||
#: 文本类 MIME 片段(命中则尝试以文本保存/HAR 内联)
|
||
TEXT_MIME_HINTS = (
|
||
"application/json",
|
||
"application/ld+json",
|
||
"application/javascript",
|
||
"application/x-javascript",
|
||
"application/xml",
|
||
"application/xhtml",
|
||
"application/x-www-form-urlencoded",
|
||
"application/graphql",
|
||
"text/",
|
||
"+json",
|
||
"+xml",
|
||
)
|
||
|
||
#: MIME → 落盘扩展名
|
||
MIME_EXT = {
|
||
"application/json": "json",
|
||
"application/ld+json": "json",
|
||
"application/javascript": "js",
|
||
"application/x-javascript": "js",
|
||
"text/javascript": "js",
|
||
"text/html": "html",
|
||
"application/xhtml+xml": "html",
|
||
"text/css": "css",
|
||
"text/xml": "xml",
|
||
"application/xml": "xml",
|
||
"text/csv": "csv",
|
||
"text/plain": "txt",
|
||
"application/x-www-form-urlencoded": "txt",
|
||
}
|
||
|
||
#: 明确不落盘的资源(无 --all-bodies 时)
|
||
SKIP_BODY_MIME_PREFIX = ("image/", "video/", "audio/", "font/")
|
||
|
||
#: POST 数据落盘上限(字节)
|
||
MAX_POST_DATA = 64 * 1024
|
||
|
||
#: 单行实时日志的 URL 显示宽度
|
||
LOG_URL_WIDTH = 110
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 小工具
|
||
# --------------------------------------------------------------------------- #
|
||
def _setup_stdout() -> None:
|
||
"""避免 Windows GBK 控制台因个别字符直接抛 UnicodeEncodeError。"""
|
||
for stream in (sys.stdout, sys.stderr):
|
||
try:
|
||
stream.reconfigure(errors="replace")
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _iso(epoch: Optional[float]) -> str:
|
||
"""epoch 秒 → 本地时区 ISO8601(带毫秒与偏移,HAR 规范要求)。"""
|
||
if not epoch:
|
||
return ""
|
||
return datetime.fromtimestamp(epoch).astimezone().isoformat(timespec="milliseconds")
|
||
|
||
|
||
def _human_size(n: Optional[int]) -> str:
|
||
if not n:
|
||
return "0B"
|
||
units = ("B", "KB", "MB", "GB")
|
||
v = float(n)
|
||
for u in units:
|
||
if v < 1024 or u == units[-1]:
|
||
return f"{v:.0f}{u}" if u == "B" else f"{v:.1f}{u}"
|
||
v /= 1024
|
||
return f"{n}B"
|
||
|
||
|
||
def _free_port() -> int:
|
||
"""取一个空闲本地端口给浏览器调试用(避免 9222 被占用)。"""
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
try:
|
||
s.bind(("127.0.0.1", 0))
|
||
return int(s.getsockname()[1])
|
||
finally:
|
||
s.close()
|
||
|
||
|
||
def _slug(url: str) -> str:
|
||
"""从 URL 抬一个安全的文件名片段。"""
|
||
name = Path(urlparse(url).path or "").name
|
||
name = re.sub(r"[^0-9A-Za-z._-]+", "_", name).strip("._-")
|
||
return name[:40] or "body"
|
||
|
||
|
||
def _ext_for(mime: str, url: str) -> str:
|
||
mime = (mime or "").split(";")[0].strip().lower()
|
||
if mime in MIME_EXT:
|
||
return MIME_EXT[mime]
|
||
suffix = Path(urlparse(url).path or "").suffix.lstrip(".").lower()
|
||
if re.fullmatch(r"[0-9a-z]{1,5}", suffix or ""):
|
||
return suffix
|
||
return "bin"
|
||
|
||
|
||
def _try_text(data: bytes) -> Optional[str]:
|
||
"""二进制看起来像文本就解码,否则返回 None。"""
|
||
if not data:
|
||
return ""
|
||
if b"\x00" in data[:2048]:
|
||
return None
|
||
try:
|
||
return data.decode("utf-8")
|
||
except UnicodeDecodeError:
|
||
return None
|
||
|
||
|
||
def _to_text_body(body: Any) -> Tuple[Optional[bytes], Optional[str]]:
|
||
"""归一化 DrissionPage 的 response.body → (原始字节, 文本或 None)。"""
|
||
if body is None:
|
||
return None, None
|
||
if isinstance(body, (dict, list)):
|
||
text = json.dumps(body, ensure_ascii=False)
|
||
return text.encode("utf-8"), text
|
||
if isinstance(body, bytes):
|
||
return body, _try_text(body)
|
||
if isinstance(body, bytearray):
|
||
raw = bytes(body)
|
||
return raw, _try_text(raw)
|
||
if isinstance(body, str):
|
||
return body.encode("utf-8", "replace"), body
|
||
return None, None
|
||
|
||
|
||
def _packet_body(resp) -> Tuple[Optional[bytes], Optional[str]]:
|
||
"""优先取 raw_body(保留服务端原始报文),拿不到再退回解析后的 body。"""
|
||
raw = getattr(resp, "raw_body", None)
|
||
is_b64 = bool(getattr(resp, "_is_base64_body", False))
|
||
if is_b64 and isinstance(raw, str):
|
||
try:
|
||
data = base64.b64decode(raw)
|
||
except Exception:
|
||
return None, None
|
||
return data, _try_text(data)
|
||
if isinstance(raw, str) and raw:
|
||
return raw.encode("utf-8", "replace"), raw
|
||
try:
|
||
return _to_text_body(resp.body)
|
||
except Exception:
|
||
return None, None
|
||
|
||
|
||
def _post_data(packet) -> Optional[str]:
|
||
"""取请求体(JSON 对象转字符串,超长截断)。"""
|
||
try:
|
||
data = packet.request.postData
|
||
except Exception:
|
||
return None
|
||
if data in (None, False, ""):
|
||
return None
|
||
if isinstance(data, (dict, list)):
|
||
text = json.dumps(data, ensure_ascii=False)
|
||
else:
|
||
text = str(data)
|
||
if len(text) > MAX_POST_DATA:
|
||
text = text[:MAX_POST_DATA] + "...<truncated>"
|
||
return text
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 浏览器定位与启动
|
||
# --------------------------------------------------------------------------- #
|
||
_CHROME_CANDIDATES = (
|
||
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
|
||
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
|
||
r"{LOCALAPPDATA}\Google\Chrome\Application\chrome.exe",
|
||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||
"/usr/bin/google-chrome",
|
||
"/usr/bin/google-chrome-stable",
|
||
"/usr/bin/chromium",
|
||
"/usr/bin/chromium-browser",
|
||
)
|
||
|
||
_EDGE_CANDIDATES = (
|
||
r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
|
||
r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
|
||
r"{LOCALAPPDATA}\Microsoft\Edge\Application\msedge.exe",
|
||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||
"/usr/bin/microsoft-edge",
|
||
"/usr/bin/microsoft-edge-stable",
|
||
)
|
||
|
||
_REG_APP_PATH = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{name}"
|
||
|
||
|
||
def _from_registry(exe_name: str) -> Optional[str]:
|
||
try:
|
||
import winreg
|
||
except ImportError:
|
||
return None
|
||
for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
|
||
for view in (0, getattr(winreg, "KEY_WOW64_64KEY", 0), getattr(winreg, "KEY_WOW64_32KEY", 0)):
|
||
try:
|
||
with winreg.OpenKey(hive, _REG_APP_PATH.format(name=exe_name), 0, winreg.KEY_READ | view) as key:
|
||
path, _ = winreg.QueryValueEx(key, "")
|
||
if path and Path(path).is_file():
|
||
return str(path)
|
||
except OSError:
|
||
continue
|
||
return None
|
||
|
||
|
||
def _resolve_browser(kind: str) -> Optional[str]:
|
||
"""auto/chrome/edge/具体路径 → 浏览器可执行文件路径(找不到返回 None)。"""
|
||
kind = (kind or "auto").strip()
|
||
if os.sep in kind or "/" in kind or kind.lower().endswith(".exe"):
|
||
return kind if Path(kind).is_file() else None
|
||
|
||
kind = kind.lower()
|
||
names = []
|
||
if kind in ("auto", "chrome"):
|
||
names.append("chrome")
|
||
if kind in ("auto", "edge"):
|
||
names.append("edge")
|
||
|
||
for name in names:
|
||
exe = "chrome.exe" if name == "chrome" else "msedge.exe"
|
||
found = _from_registry(exe)
|
||
if found:
|
||
return found
|
||
for pattern in (_CHROME_CANDIDATES if name == "chrome" else _EDGE_CANDIDATES):
|
||
candidate = pattern.format(LOCALAPPDATA=os.environ.get("LOCALAPPDATA", ""))
|
||
if Path(candidate).is_file():
|
||
return candidate
|
||
return None
|
||
|
||
|
||
def _probe_debug_port(port: int) -> Tuple[bool, bool]:
|
||
"""探测调试端口:返回 (是否可用, 是否无头浏览器)。
|
||
|
||
DrissionPage 连接已有实例时,若「实际无头」与 options 里的 headless 不一致,
|
||
会先 quit() 杀掉浏览器再自己重启(见 Chromium.__init__ 的无头校验),
|
||
所以 attach 之前必须先探明无头状态,避免误杀用户浏览器。
|
||
"""
|
||
import urllib.request
|
||
|
||
try:
|
||
with urllib.request.urlopen(f"http://127.0.0.1:{port}/json/version", timeout=3) as resp:
|
||
info = json.loads(resp.read().decode("utf-8", "replace") or "{}")
|
||
except Exception:
|
||
return False, False
|
||
ua = str(info.get("User-Agent") or info.get("Browser") or "").lower()
|
||
return True, "headless" in ua
|
||
|
||
|
||
def _launch_browser(args) -> Tuple[Any, bool]:
|
||
"""返回 (page, 是否由本工具启动)。"""
|
||
from DrissionPage import ChromiumOptions, ChromiumPage
|
||
|
||
# read_file=False:不吃本机 DrissionPage 全局配置,行为可复现
|
||
opt = ChromiumOptions(read_file=False)
|
||
|
||
if args.attach_port:
|
||
alive, headless = _probe_debug_port(args.attach_port)
|
||
if not alive:
|
||
raise RuntimeError(
|
||
f"127.0.0.1:{args.attach_port} 上没有可用的调试端口。\n"
|
||
f"启动示例:msedge.exe --remote-debugging-port={args.attach_port} --remote-allow-origins=*")
|
||
opt.set_address(f"127.0.0.1:{args.attach_port}")
|
||
opt.existing_only(True)
|
||
if headless:
|
||
opt.headless(True) # 仅用于对齐 DrissionPage 的无头判断,不会真正启动浏览器
|
||
page = ChromiumPage(opt)
|
||
return page, False
|
||
|
||
exe = _resolve_browser(args.browser)
|
||
if exe:
|
||
opt.set_browser_path(exe)
|
||
elif args.browser and args.browser.lower() != "auto":
|
||
raise RuntimeError(f"未找到浏览器:{args.browser},请用 --browser 指定可执行文件路径")
|
||
|
||
profile = Path(args._profile_dir)
|
||
profile.mkdir(parents=True, exist_ok=True)
|
||
opt.set_user_data_path(str(profile))
|
||
opt.set_local_port(args._port or _free_port())
|
||
opt.set_argument("--no-first-run")
|
||
opt.set_argument("--no-default-browser-check")
|
||
opt.set_argument("--disable-background-networking")
|
||
opt.set_argument("--disable-features=Translate,OptimizationHints,MediaRouter")
|
||
if args.headless:
|
||
opt.headless(True)
|
||
|
||
page = ChromiumPage(opt)
|
||
return page, True
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 抓包记录器
|
||
# --------------------------------------------------------------------------- #
|
||
class Recorder(object):
|
||
"""把 DataPacket 转成结构化记录,实时写 JSONL,退出时出 HAR/CSV。"""
|
||
|
||
def __init__(self, run_dir: Path, args) -> None:
|
||
self.run_dir = run_dir
|
||
self.args = args
|
||
self.records: List[Dict[str, Any]] = []
|
||
self.seq = 0
|
||
self.body_files = 0
|
||
self._excludes = [re.compile(p, re.I) for p in (args.exclude or [])]
|
||
self.bodies_dir = run_dir / "bodies"
|
||
if args.save_bodies:
|
||
self.bodies_dir.mkdir(parents=True, exist_ok=True)
|
||
self.jsonl_path = run_dir / "capture.jsonl"
|
||
self._fh = self.jsonl_path.open("w", encoding="utf-8", newline="\n")
|
||
self.started_at = time.time()
|
||
|
||
# -- 过滤 ---------------------------------------------------------- #
|
||
def _accept(self, url: str) -> bool:
|
||
if not url or url.startswith(("data:", "blob:", "chrome-extension:")):
|
||
return False
|
||
return not any(rx.search(url) for rx in self._excludes)
|
||
|
||
# -- 主入口 -------------------------------------------------------- #
|
||
def add(self, tab_id: str, packet) -> Optional[Dict[str, Any]]:
|
||
url = getattr(packet, "url", "") or ""
|
||
if not self._accept(url):
|
||
return None
|
||
|
||
self.seq += 1
|
||
idx = self.seq
|
||
now = time.time()
|
||
raw_req = getattr(packet, "_raw_request", None) or {}
|
||
raw_resp = getattr(packet, "_raw_response", None) or {}
|
||
started_epoch = raw_req.get("wallTime") or now
|
||
|
||
method = getattr(packet, "method", "") or ""
|
||
res_type = getattr(packet, "resourceType", None) or raw_req.get("type") or ""
|
||
failed = bool(getattr(packet, "is_failed", False))
|
||
error_text = ""
|
||
if failed:
|
||
try:
|
||
error_text = packet.fail_info.errorText or packet.fail_info.blockedReason or "failed"
|
||
except Exception:
|
||
error_text = "failed"
|
||
|
||
status: Optional[int] = None
|
||
status_text = ""
|
||
mime = ""
|
||
resp_headers: Dict[str, str] = {}
|
||
body_file: Optional[str] = None
|
||
body_size = 0
|
||
body_is_text = False
|
||
encoded_len = 0
|
||
remote_ip = ""
|
||
protocol = ""
|
||
from_cache = False
|
||
|
||
timing = raw_resp.get("timing") or {}
|
||
timing_send = _timing_delta(timing, "sendStart", "sendEnd")
|
||
timing_wait = _timing_delta(timing, "sendEnd", "receiveHeadersEnd")
|
||
|
||
if raw_resp:
|
||
try:
|
||
resp = packet.response
|
||
status = resp.status
|
||
status_text = resp.statusText or ""
|
||
mime = resp.mimeType or ""
|
||
resp_headers = {str(k): str(v) for k, v in dict(resp.headers).items()}
|
||
encoded_len = int(raw_resp.get("encodedDataLength") or 0)
|
||
remote_ip = raw_resp.get("remoteIPAddress") or ""
|
||
protocol = raw_resp.get("protocol") or ""
|
||
from_cache = bool(resp.fromDiskCache or resp.fromServiceWorker)
|
||
raw_body, text = _packet_body(resp)
|
||
if raw_body:
|
||
body_size = len(raw_body)
|
||
body_file, body_is_text = self._save_body(idx, url, mime, raw_body, text)
|
||
except Exception:
|
||
pass
|
||
|
||
duration_ms = max(0, int(round((now - float(started_epoch)) * 1000))) if started_epoch else 0
|
||
if timing_send >= 0 and timing_wait >= 0:
|
||
duration_ms = max(duration_ms, int(round(timing_send + timing_wait)))
|
||
|
||
record: Dict[str, Any] = {
|
||
"i": idx,
|
||
"ts": _iso(now),
|
||
"started": _iso(float(started_epoch)),
|
||
"tab": tab_id,
|
||
"method": method,
|
||
"url": url,
|
||
"status": status,
|
||
"status_text": status_text,
|
||
"mime": mime,
|
||
"type": res_type,
|
||
"req_headers": self._headers_of(packet, request=True),
|
||
"resp_headers": resp_headers,
|
||
"post_data": _post_data(packet),
|
||
"body_file": body_file,
|
||
"body_size": body_size,
|
||
"body_is_text": body_is_text,
|
||
"encoded_len": encoded_len,
|
||
"duration_ms": duration_ms,
|
||
"timing_send": round(timing_send, 2),
|
||
"timing_wait": round(timing_wait, 2),
|
||
"remote_ip": remote_ip,
|
||
"protocol": protocol,
|
||
"from_cache": from_cache,
|
||
"failed": failed,
|
||
"error": error_text,
|
||
}
|
||
self.records.append(record)
|
||
self._fh.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||
self._fh.flush()
|
||
return record
|
||
|
||
@staticmethod
|
||
def _headers_of(packet, request: bool = False) -> Dict[str, str]:
|
||
try:
|
||
hdrs = packet.request.headers if request else packet.response.headers
|
||
return {str(k): str(v) for k, v in dict(hdrs).items()}
|
||
except Exception:
|
||
return {}
|
||
|
||
# -- 响应体落盘 ---------------------------------------------------- #
|
||
def _save_body(self, idx: int, url: str, mime: str, raw: bytes,
|
||
text: Optional[str]) -> Tuple[Optional[str], bool]:
|
||
if not self.args.save_bodies or len(raw) > self.args.max_body:
|
||
return None, False
|
||
mime_l = (mime or "").lower()
|
||
if text is None and not self.args.all_bodies:
|
||
return None, False
|
||
if not self.args.all_bodies and mime_l.startswith(SKIP_BODY_MIME_PREFIX):
|
||
return None, False
|
||
|
||
ext = _ext_for(mime, url)
|
||
name = f"{idx:05d}_{_slug(url)}.{ext}"
|
||
path = self.bodies_dir / name
|
||
try:
|
||
if text is not None and body_is_text_mime(mime):
|
||
path.write_text(text, encoding="utf-8", errors="replace")
|
||
else:
|
||
path.write_bytes(raw)
|
||
except OSError:
|
||
return None, False
|
||
self.body_files += 1
|
||
return str(path.relative_to(self.run_dir)), text is not None
|
||
|
||
# -- 输出 ---------------------------------------------------------- #
|
||
def close(self) -> Dict[str, Any]:
|
||
try:
|
||
self._fh.close()
|
||
except Exception:
|
||
pass
|
||
if self.args.save_har:
|
||
self._write_har()
|
||
self._write_csv()
|
||
return {
|
||
"total": len(self.records),
|
||
"failed": sum(1 for r in self.records if r["failed"]),
|
||
"bodies": self.body_files,
|
||
"by_type": Counter(r["type"] or "Other" for r in self.records),
|
||
"bad_status": [r for r in self.records if r["status"] and int(r["status"]) >= 400],
|
||
"started_at": self.started_at,
|
||
"ended_at": time.time(),
|
||
}
|
||
|
||
def _har_entry(self, r: Dict[str, Any]) -> Dict[str, Any]:
|
||
total = int(r["duration_ms"] or 0)
|
||
send = float(r.get("timing_send") or 0)
|
||
wait = float(r.get("timing_wait") or 0)
|
||
if send < 0:
|
||
send = 0
|
||
if wait < 0:
|
||
wait = max(0, total - send)
|
||
receive = max(0, total - send - wait)
|
||
|
||
content: Dict[str, Any] = {"size": int(r["body_size"] or 0), "mimeType": r["mime"] or ""}
|
||
body_path = r.get("body_file")
|
||
if body_path:
|
||
full = self.run_dir / body_path
|
||
try:
|
||
if r.get("body_is_text"):
|
||
content["text"] = full.read_text(encoding="utf-8", errors="replace")
|
||
else:
|
||
content["text"] = base64.b64encode(full.read_bytes()).decode("ascii")
|
||
content["encoding"] = "base64"
|
||
except OSError:
|
||
pass
|
||
|
||
req_headers = [{"name": k, "value": v} for k, v in (r["req_headers"] or {}).items()]
|
||
resp_headers = [{"name": k, "value": v} for k, v in (r["resp_headers"] or {}).items()]
|
||
location = ""
|
||
for k, v in (r["resp_headers"] or {}).items():
|
||
if k.lower() == "location":
|
||
location = v
|
||
break
|
||
|
||
request: Dict[str, Any] = {
|
||
"method": r["method"] or "GET",
|
||
"url": r["url"],
|
||
"httpVersion": "HTTP/1.1",
|
||
"cookies": [],
|
||
"headers": req_headers,
|
||
"queryString": [{"name": k, "value": v}
|
||
for k, v in parse_qsl(urlparse(r["url"]).query, keep_blank_values=True)],
|
||
"headersSize": -1,
|
||
"bodySize": len((r.get("post_data") or "").encode("utf-8")),
|
||
}
|
||
if r.get("post_data"):
|
||
request["postData"] = {"mimeType": _req_mime(r), "text": r["post_data"]}
|
||
|
||
response: Dict[str, Any] = {
|
||
"status": int(r["status"] or 0),
|
||
"statusText": r["status_text"] or "",
|
||
"httpVersion": r["protocol"] or "HTTP/1.1",
|
||
"cookies": [],
|
||
"headers": resp_headers,
|
||
"content": content,
|
||
"redirectURL": location,
|
||
"headersSize": -1,
|
||
"bodySize": int(r["encoded_len"] or 0),
|
||
"_error": r["error"] or None,
|
||
}
|
||
return {
|
||
"startedDateTime": r["started"] or r["ts"],
|
||
"time": send + wait + receive,
|
||
"request": request,
|
||
"response": response,
|
||
"cache": {},
|
||
"timings": {"blocked": -1, "dns": -1, "connect": -1, "ssl": -1,
|
||
"send": send, "wait": wait, "receive": receive},
|
||
"serverIPAddress": r["remote_ip"] or "",
|
||
"connection": "",
|
||
"comment": r["type"] or "",
|
||
}
|
||
|
||
def _write_har(self) -> None:
|
||
# 私有字段只在内存里,写 HAR 前临时补上 timing 需要的信息
|
||
entries = [self._har_entry(r) for r in self.records]
|
||
har = {
|
||
"log": {
|
||
"version": "1.2",
|
||
"creator": {"name": "37du net_capture", "version": TOOL_VERSION},
|
||
"pages": [],
|
||
"entries": entries,
|
||
}
|
||
}
|
||
(self.run_dir / "netcap.har").write_text(
|
||
json.dumps(har, ensure_ascii=False, indent=1), encoding="utf-8")
|
||
|
||
def _write_csv(self) -> None:
|
||
path = self.run_dir / "requests.csv"
|
||
with path.open("w", encoding="utf-8-sig", newline="") as fh:
|
||
writer = csv.writer(fh)
|
||
writer.writerow(["序号", "时间", "方法", "状态", "类型", "MIME", "大小", "响应体", "URL"])
|
||
for r in self.records:
|
||
writer.writerow([
|
||
r["i"], r["ts"], r["method"], r["status"] or "", r["type"],
|
||
r["mime"], _human_size(r["body_size"]), r["body_file"] or "", r["url"],
|
||
])
|
||
|
||
|
||
def body_is_text_mime(mime: str) -> bool:
|
||
mime = (mime or "").lower()
|
||
return any(h in mime for h in TEXT_MIME_HINTS)
|
||
|
||
|
||
def _timing_delta(timing: Dict[str, Any], a: str, b: str) -> float:
|
||
"""CDP ResourceTiming 的各阶段字段是「相对 requestTime 的毫秒数」,直接相减。"""
|
||
va, vb = timing.get(a), timing.get(b)
|
||
if isinstance(va, (int, float)) and isinstance(vb, (int, float)) and va >= 0 and vb >= 0:
|
||
return max(0.0, float(vb) - float(va))
|
||
return -1.0
|
||
|
||
|
||
def _req_mime(r: Dict[str, Any]) -> str:
|
||
for k, v in (r["req_headers"] or {}).items():
|
||
if k.lower() == "content-type":
|
||
return v
|
||
return ""
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 标签页监听管理
|
||
# --------------------------------------------------------------------------- #
|
||
class TabCapture(object):
|
||
"""一个标签页 = 一个 DrissionPage 监听器。"""
|
||
|
||
def __init__(self, tab, args) -> None:
|
||
self.tab = tab
|
||
self.tab_id = tab.tab_id
|
||
self.label = self.tab_id[:6]
|
||
self._listener = tab.listen
|
||
self.args = args
|
||
|
||
def start(self) -> None:
|
||
targets = list(self.args.target) if self.args.target else True
|
||
kwargs: Dict[str, Any] = {"targets": targets, "is_regex": self.args.regex if self.args.target else None}
|
||
if self.args.method:
|
||
kwargs["method"] = [m.upper() for m in self.args.method]
|
||
if self.args.res_type:
|
||
kwargs["res_type"] = [t.upper() for t in self.args.res_type]
|
||
# method=None 时 DrissionPage 保留默认 GET/POST,必须显式 True 才能全方法
|
||
if not self.args.method:
|
||
kwargs["method"] = True
|
||
self._listener.start(**kwargs)
|
||
|
||
def drain(self, recorder: Recorder) -> int:
|
||
"""尽量取空监听队列。直接用内部队列,避免 wait() 的空转与边界 bug。"""
|
||
queue = getattr(self._listener, "_caught", None)
|
||
if queue is None: # 兼容未来版本
|
||
try:
|
||
packet = self._listener.wait(count=1, timeout=0.05)
|
||
except Exception:
|
||
return 0
|
||
if not packet:
|
||
return 0
|
||
recorder.add(self.tab_id, packet)
|
||
return 1
|
||
n = 0
|
||
while True:
|
||
try:
|
||
packet = queue.get_nowait()
|
||
except Exception:
|
||
break
|
||
try:
|
||
recorder.add(self.tab_id, packet)
|
||
except Exception:
|
||
pass
|
||
n += 1
|
||
return n
|
||
|
||
def stop(self) -> None:
|
||
try:
|
||
self._listener.stop()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 日志
|
||
# --------------------------------------------------------------------------- #
|
||
def log_packet(rec: Optional[Dict[str, Any]], total: int) -> None:
|
||
if not rec:
|
||
return
|
||
status = rec["status"] if rec["status"] is not None else ("ERR" if rec["failed"] else "-")
|
||
url = rec["url"]
|
||
if len(url) > LOG_URL_WIDTH:
|
||
url = url[:LOG_URL_WIDTH] + "..."
|
||
mime = (rec["mime"] or "").split(";")[0]
|
||
size = _human_size(rec["body_size"] or rec["encoded_len"])
|
||
print(f"[{total:>4}] {str(status):>4} {rec['method']:<6} {(rec['type'] or '-'):<11} "
|
||
f"{size:>7} {mime:<24} {url}")
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 主流程
|
||
# --------------------------------------------------------------------------- #
|
||
def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
|
||
p = argparse.ArgumentParser(
|
||
prog="net_capture.py",
|
||
description="用 DrissionPage 打开浏览器并记录所有网络请求(抓包)。",
|
||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||
epilog="示例:.venv\\Scripts\\python.exe tools\\net_capture.py --url https://example.com",
|
||
)
|
||
p.add_argument("--url", default=None, help="启动后立即打开的网址")
|
||
p.add_argument("--browser", default="auto",
|
||
help="auto / chrome / edge / 浏览器 exe 路径,默认 auto")
|
||
p.add_argument("--port", type=int, default=0, help="浏览器调试端口,0=自动挑空闲端口")
|
||
p.add_argument("--attach-port", type=int, default=0,
|
||
help="连接已存在的调试端口(如 9222),不新开浏览器")
|
||
p.add_argument("--profile-dir", default=None, help="浏览器用户数据目录(保留登录态)")
|
||
p.add_argument("--temp-profile", action="store_true", help="用一次性临时用户目录(不保留登录态)")
|
||
p.add_argument("--headless", action="store_true", help="无头模式(配合 --duration 做脚本化采集)")
|
||
p.add_argument("--target", action="append", default=[], help="只抓 URL 含该关键词的请求,可多次")
|
||
p.add_argument("--regex", action="store_true", help="--target 按正则解释")
|
||
p.add_argument("--exclude", action="append", default=[], help="排除 URL 匹配该正则的请求,可多次")
|
||
p.add_argument("--res-type", action="append", default=[],
|
||
help="只抓指定资源类型(XHR Fetch Document Script Image ...),可多次")
|
||
p.add_argument("--method", action="append", default=[], help="只抓指定方法(GET POST ...),默认全部")
|
||
p.add_argument("--no-bodies", dest="save_bodies", action="store_false", help="不保存响应体")
|
||
p.add_argument("--all-bodies", action="store_true", help="连二进制响应体(图片/字体等)也落盘")
|
||
p.add_argument("--max-body", type=int, default=2 * 1024 * 1024, help="单个响应体落盘上限(字节)")
|
||
p.add_argument("--no-har", dest="save_har", action="store_false", help="不生成 HAR")
|
||
p.add_argument("--out-dir", default=str(REPO_ROOT / "out" / "netcap"), help="输出根目录")
|
||
p.add_argument("--duration", type=float, default=0, help="抓包时长(秒),0=直到关闭浏览器或 Ctrl+C")
|
||
p.add_argument("--keep-open", action="store_true", help="结束后不关闭本工具启动的浏览器")
|
||
p.add_argument("--quiet", action="store_true", help="不打印每条请求")
|
||
p.add_argument("--version", action="version", version=f"net_capture {TOOL_VERSION}")
|
||
p.set_defaults(save_bodies=True, save_har=True)
|
||
return p.parse_args(argv)
|
||
|
||
|
||
def main(argv: Optional[List[str]] = None) -> int:
|
||
_setup_stdout()
|
||
args = parse_args(argv)
|
||
|
||
if not args.attach_port and args.port and not (1 <= args.port <= 65535):
|
||
print("[错误] --port 超出范围", file=sys.stderr)
|
||
return 2
|
||
|
||
for pattern in args.exclude:
|
||
try:
|
||
re.compile(pattern)
|
||
except re.error as exc:
|
||
print(f"[错误] --exclude 正则非法:{pattern}({exc})", file=sys.stderr)
|
||
return 2
|
||
if args.target and args.regex:
|
||
for pattern in args.target:
|
||
try:
|
||
re.compile(pattern)
|
||
except re.error as exc:
|
||
print(f"[错误] --target 正则非法:{pattern}({exc})", file=sys.stderr)
|
||
return 2
|
||
|
||
run_root = Path(args.out_dir).expanduser().resolve()
|
||
run_dir = run_root / datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
try:
|
||
run_dir.mkdir(parents=True, exist_ok=True)
|
||
except OSError as exc:
|
||
print(f"[错误] 无法创建输出目录 {run_dir}:{exc}", file=sys.stderr)
|
||
return 2
|
||
|
||
args._port = args.port
|
||
if args.profile_dir:
|
||
args._profile_dir = str(Path(args.profile_dir).expanduser().resolve())
|
||
elif args.temp_profile:
|
||
args._profile_dir = str(run_dir / "profile")
|
||
else:
|
||
args._profile_dir = str((run_root / "profile").resolve())
|
||
|
||
print(f"输出目录:{run_dir}")
|
||
if not args.attach_port:
|
||
print(f"用户数据目录:{args._profile_dir}")
|
||
|
||
# ---- 启动浏览器 ----
|
||
try:
|
||
page, launched = _launch_browser(args)
|
||
except Exception as exc:
|
||
print(f"[错误] 浏览器启动失败:{exc}", file=sys.stderr)
|
||
print(" 排查:关闭同用户数据目录的浏览器窗口;或用 --temp-profile / --attach-port。",
|
||
file=sys.stderr)
|
||
return 4
|
||
|
||
print(f"浏览器已就绪:{getattr(page, 'address', '-')} ({'本工具启动' if launched else '已存在实例'})")
|
||
|
||
recorder = Recorder(run_dir, args)
|
||
caps: Dict[str, TabCapture] = {}
|
||
|
||
def sync_tabs() -> List[str]:
|
||
try:
|
||
tab_ids = list(page.browser.tab_ids)
|
||
except Exception:
|
||
return []
|
||
for tid in tab_ids:
|
||
if tid in caps:
|
||
continue
|
||
try:
|
||
cap = TabCapture(page.get_tab(tid), args)
|
||
cap.start()
|
||
caps[tid] = cap
|
||
if not args.quiet:
|
||
print(f" + 开始监听标签页 {cap.label}")
|
||
except Exception:
|
||
continue
|
||
for tid in list(caps):
|
||
if tid not in tab_ids:
|
||
caps[tid].drain(recorder)
|
||
caps.pop(tid).stop()
|
||
return tab_ids
|
||
|
||
sync_tabs()
|
||
if not caps:
|
||
print("[错误] 没有可监听的标签页", file=sys.stderr)
|
||
recorder.close()
|
||
return 3
|
||
|
||
if args.url:
|
||
try:
|
||
page.get(args.url)
|
||
except Exception as exc:
|
||
print(f"[警告] 打开 {args.url} 失败:{exc}")
|
||
|
||
deadline = time.time() + args.duration if args.duration > 0 else 0
|
||
print("开始抓包:在浏览器里正常操作即可,Ctrl+C 或关闭浏览器结束。")
|
||
|
||
stopped = False
|
||
summary: Optional[Dict[str, Any]] = None
|
||
try:
|
||
while True:
|
||
for cap in list(caps.values()):
|
||
try:
|
||
total_before = len(recorder.records)
|
||
cap.drain(recorder)
|
||
if not args.quiet:
|
||
for rec in recorder.records[total_before:]:
|
||
log_packet(rec, int(rec.get("i") or 0))
|
||
except Exception:
|
||
pass
|
||
|
||
if deadline and time.time() >= deadline:
|
||
print("到达 --duration 指定时长,停止抓包。")
|
||
break
|
||
|
||
if not page.browser.states.is_alive:
|
||
print("浏览器已关闭,停止抓包。")
|
||
break
|
||
|
||
tab_ids = sync_tabs()
|
||
if launched and not tab_ids:
|
||
print("所有标签页已关闭,停止抓包。")
|
||
break
|
||
|
||
time.sleep(0.1)
|
||
except KeyboardInterrupt:
|
||
print("\n收到 Ctrl+C,停止抓包。")
|
||
stopped = True
|
||
finally:
|
||
for cap in list(caps.values()):
|
||
try:
|
||
cap.drain(recorder)
|
||
except Exception:
|
||
pass
|
||
cap.stop()
|
||
caps.clear()
|
||
|
||
summary = recorder.close()
|
||
|
||
if launched and not args.keep_open:
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
if summary is None:
|
||
print("[错误] 抓包过程异常,未能生成汇总", file=sys.stderr)
|
||
return 3
|
||
_write_meta(run_dir, args, summary)
|
||
_print_summary(run_dir, summary, stopped)
|
||
return 0
|
||
|
||
|
||
def _write_meta(run_dir: Path, args, summary: Dict[str, Any]) -> None:
|
||
meta = {
|
||
"tool": "net_capture.py",
|
||
"version": TOOL_VERSION,
|
||
"args": {k: v for k, v in vars(args).items() if not k.startswith("_")},
|
||
"started_at": _iso(summary["started_at"]),
|
||
"ended_at": _iso(summary["ended_at"]),
|
||
"total": summary["total"],
|
||
"failed": summary["failed"],
|
||
"body_files": summary["bodies"],
|
||
"by_type": dict(summary["by_type"]),
|
||
}
|
||
try:
|
||
(run_dir / "meta.json").write_text(
|
||
json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _print_summary(run_dir: Path, summary: Dict[str, Any], stopped: bool) -> None:
|
||
total = summary["total"]
|
||
print("\n" + "=" * 72)
|
||
print(f"抓包结束:共 {total} 条请求,加载失败 {summary['failed']} 条,"
|
||
f"4xx/5xx {len(summary['bad_status'])} 条,响应体 {summary['bodies']} 个")
|
||
if summary["by_type"]:
|
||
detail = " ".join(f"{k}:{v}" for k, v in summary["by_type"].most_common())
|
||
print(f"资源类型:{detail}")
|
||
for rec in summary["bad_status"][:10]:
|
||
print(f" ! {rec['status']} {rec['method']} {rec['url'][:100]}")
|
||
|
||
print("输出文件:")
|
||
print(f" JSONL : {run_dir / 'capture.jsonl'}")
|
||
if Path(run_dir / "netcap.har").exists():
|
||
print(f" HAR : {run_dir / 'netcap.har'} (可拖入 Chrome DevTools → Network)")
|
||
print(f" CSV : {run_dir / 'requests.csv'}")
|
||
if summary["bodies"]:
|
||
print(f" 响应体: {run_dir / 'bodies'}")
|
||
print(f" 元信息: {run_dir / 'meta.json'}")
|
||
if stopped:
|
||
print("提示:已抓到的数据均已落盘,可直接分析。")
|
||
print("=" * 72)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|