135 lines
4.7 KiB
Python
135 lines
4.7 KiB
Python
"""打开 lotsmall 管理端,捕获所有标签页的接口请求(用于摸清导出接口)。
|
|
|
|
用法:
|
|
1. 运行本脚本:.venv\\Scripts\\python.exe tests/lotsmall_probe/lotsmall_capture.py
|
|
2. 在弹出的浏览器里手动登录 → 进报表页 → 导出
|
|
3. 完成后回终端告诉我
|
|
|
|
捕获文件:%TEMP%\\lotsmall_capture\\capture_<时间>.jsonl
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import time
|
|
from datetime import datetime
|
|
from urllib.parse import urlparse
|
|
|
|
from DrissionPage import ChromiumOptions, ChromiumPage
|
|
|
|
# ==================== 配置 ====================
|
|
START_URL = "https://www.lotsmall.cn/manage/TicketInspectorReport"
|
|
PROFILE_DIR = os.path.join(os.environ.get("TEMP", "."), "lotsmall_profile")
|
|
OUT_DIR = os.path.join(os.environ.get("TEMP", "."), "lotsmall_capture")
|
|
MAX_MINUTES = 60
|
|
SKIP_TYPES = {"Stylesheet", "Script", "Image", "Font", "Media", "Manifest", "TextTrack"}
|
|
STATIC_RE = re.compile(r"\.(js|css|png|jpe?g|gif|svg|woff2?|ico|map)(\?|$)", re.I)
|
|
# =============================================
|
|
|
|
os.makedirs(OUT_DIR, exist_ok=True)
|
|
LOG_PATH = os.path.join(OUT_DIR, f"capture_{datetime.now():%Y%m%d_%H%M%S}.jsonl")
|
|
|
|
|
|
def record(packet, fh):
|
|
if packet.resourceType in SKIP_TYPES:
|
|
return
|
|
if STATIC_RE.search(packet.url) and packet.resourceType not in ("Document", "XHR", "Fetch"):
|
|
return
|
|
|
|
req, resp = packet.request, packet.response
|
|
if req is None and resp is None:
|
|
return
|
|
|
|
def to_dict(h):
|
|
try:
|
|
return dict(h) if h else None
|
|
except Exception:
|
|
return None
|
|
|
|
body = None
|
|
if resp is not None:
|
|
try:
|
|
body = resp.body
|
|
except Exception:
|
|
body = None
|
|
if isinstance(body, bytes):
|
|
body = f"<binary {len(body)} bytes>" if len(body) > 20000 else body[:2000].decode("utf-8", "replace")
|
|
elif isinstance(body, str) and len(body) > 60000:
|
|
body = body[:60000]
|
|
|
|
post = getattr(req, "postData", None) if req else None
|
|
if isinstance(post, bytes):
|
|
post = f"<binary {len(post)} bytes>"
|
|
|
|
rec = {
|
|
"time": datetime.now().strftime("%H:%M:%S"),
|
|
"method": packet.method,
|
|
"url": packet.url,
|
|
"type": packet.resourceType,
|
|
"status": getattr(resp, "status", None) if resp else None,
|
|
"reqHeaders": to_dict(getattr(req, "headers", None)) if req else None,
|
|
"postData": post,
|
|
"respHeaders": to_dict(getattr(resp, "headers", None)) if resp else None,
|
|
"resp": body,
|
|
}
|
|
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
fh.flush()
|
|
print(f"[{rec['type']}] {rec['method']} {rec['status']} {packet.url.split('?')[0]}", flush=True)
|
|
|
|
|
|
def main():
|
|
co = ChromiumOptions()
|
|
co.headless(False)
|
|
co.set_user_data_path(PROFILE_DIR)
|
|
co.set_argument("--start-maximized")
|
|
# 报表页嵌在 platform-report-sh1.zhiyoubao.com 的跨域 iframe 里,
|
|
# 默认站点隔离会把它放到独立进程导致抓不到请求,这里关掉隔离
|
|
co.set_argument("--disable-features=IsolateOrigins,site-per-process")
|
|
co.set_argument("--disable-site-isolation-trials")
|
|
page = ChromiumPage(co)
|
|
|
|
page.get(START_URL)
|
|
time.sleep(3)
|
|
print("当前地址:", page.url, flush=True)
|
|
print(f"接口日志:{LOG_PATH}", flush=True)
|
|
print("请手动登录并操作导出,完成后告诉我。", flush=True)
|
|
|
|
page.listen.start(targets=True)
|
|
tabs = {page.tab_id: page}
|
|
deadline = time.time() + MAX_MINUTES * 60
|
|
last_scan = 0
|
|
try:
|
|
with open(LOG_PATH, "a", encoding="utf-8") as fh:
|
|
while time.time() < deadline:
|
|
if time.time() - last_scan > 2:
|
|
last_scan = time.time()
|
|
for t in page.get_tabs():
|
|
if t.tab_id not in tabs:
|
|
try:
|
|
t.listen.start(targets=True)
|
|
tabs[t.tab_id] = t
|
|
print(f"[新标签页] {t.url}", flush=True)
|
|
except Exception:
|
|
pass
|
|
|
|
idle = True
|
|
for t in list(tabs.values()):
|
|
try:
|
|
pkt = t.listen.wait(count=1, timeout=0.2)
|
|
except Exception:
|
|
continue
|
|
if not pkt:
|
|
continue
|
|
idle = False
|
|
for p in (pkt if isinstance(pkt, list) else [pkt]):
|
|
record(p, fh)
|
|
if idle:
|
|
time.sleep(0.2)
|
|
finally:
|
|
page.listen.stop()
|
|
print("日志已保存:", LOG_PATH, flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|