Files
37duAutomation/tests/tianque_probe/tianque_report_capture.py
T
puddy e4539db9f8 chore(tests): 新增天阙平台探测脚本并清理临时脚本
- tests/tianque_probe:天阙会生活商户平台登录(drission)/报表抓包/导出探测脚本,供 XQ0079 排查字段与接口用

- 删除临时脚本 .tmp_check_wf0033.py
2026-11-06 15:52:24 +08:00

394 lines
16 KiB
Python
Raw 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.
"""天阙会生活商户平台:用 DrissionPage 真浏览器登录后监听报表类接口,产出可复现的抓包样本。
用法:
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_report_capture.py
MODE = "auto" 登录后按 REPORT_ROUTES 逐页打开,自动触发报表/账单页的接口
MODE = "manual" 登录后只开监听,你自己在页面里点报表菜单(最省事,推荐第一次用)
产出(CAPTURE_DIR/<时间戳>/):
packets.jsonl 每一条接口调用一行:method / url / 参数 / 响应 code / 响应体(截断)
apis.json 按接口去重的清单:调用次数、示例参数、响应结构、成功码,用于后续写采集器
files/ 二进制响应(导出 Excel/CSV/ZIP)原样落盘
capture.log 控制台同步日志
抓包原理:page.listen.start() 全量监听(CDP Network),不依赖页面 JS hook,
RPA 常用的「查询列表 + 轮询 download/polling + download/downLoad/<id>」两段式导出也能抓到。
已知坑位:
- 前端 POST body 可能是 {"header":{"sysType":"pc"},"data":{...}} 信封,也可能是扁平结构,
抓到的 postData 是原始报文,写采集器时照抄即可。
- 导出类接口多为两段:先提交任务拿 id,再 GET download/downLoad/<id> 取文件;
第二段可能不返回可读 body,只记 URL。
- 登录后前端用 sessionStorage.user 存 token,业务接口靠请求头 token + channel。
"""
import json
import os
import re
import sys
import time
from datetime import datetime
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
# ==================== 配置区 ====================
MODE = "manual" # auto=自动逐页开;manual=只监听,你手点
DO_LOGIN = True # False 时不自动登录(浏览器里已登录过就直接监听)
HEADLESS = False # 报表页多为图表,无头也可以,但 OCR 识别率略低
IDLE_SECONDS = 90 # 多久没有「有新意的」接口调用就结束监听
MAX_SECONDS = 1800 # 整轮监听总时长上限(秒)
PAGE_WAIT = 10 # auto 模式每页打开后等待渲染的秒数
PAGE_LISTEN = 25 # auto 模式单页最多听多少秒
MAX_BODY_CHARS = 20000 # 单条响应体落盘截断长度
CAPTURE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "capture")
# 只收这些接口(None=全收):默认只留业务接口,滤掉埋点/日志/静态资源
KEEP_KEYWORDS = ("/management/easypay/api/", "/api/")
SKIP_KEYWORDS = ("/log", "/monitor", "/heartbeat", "/reportData", ".js", ".css", ".png",
".jpg", ".svg", ".woff", ".ttf", "sentry", "collect")
# 高频背景轮询:照常落盘,但不刷屏、也不重置空闲计时(否则永远等不到空闲)
NOISE_KEYWORDS = ("/download/polling", "/messageManage/queryUnReadMsgCount", "/creditSwitch/",
"/user/activityInfo", "/agentAd/getAdInfo")
# auto 模式要走的报表页(来自前端 bundle 的 umi 路由表,可按需增删)
REPORT_ROUTES = [
("交易趋势", "/report/trend"),
("交易排行", "/report/ranking"),
("分店报表", "/report/branch"),
("即时门店", "/report/jiShiStore"),
("即时台账", "/report/jiShiLedgerAccount"),
("明细账单", "/reconciliation/itemizedBill"),
("汇总账单", "/reconciliation/totalBill"),
("结算管理", "/financialData/settlementManage"),
("账单管理", "/financialData/billManage"),
("凭证管理", "/financialData/voucherManage"),
]
# 从 bundle 里扒出来的报表相关接口,manual 模式打印出来给你当「点哪里」的对照表
EXPECTED_APIS = [
"/tranInfoPc/tradeReport", # 交易报表主查询
"/tranInfoPc/tradeReportAmtSum", # 交易报表金额汇总
"/tranInfoPc/queryTradeMark", # 交易报表打点/标签
"/tranInfoPc/queryMnoTradeRank", # 商户交易排行
"/tranInfoPc/tranListByParamNew", # 交易明细列表
"/tranInfoPc/transactionTrad", # 交易笔数
"/tranInfoPc/downloadTradeReport", # 交易报表导出
"/tranInfoPc/downloadStatement", # 对账单下载
"/tranInfoPc/downloadTradList", # 交易明细下载
"/tranInfoPc/exportNew", # 通用导出
"/tranInfo/queryTranSumByDate", # 按日交易汇总
"/tranInfo/queryTradeSumByMonth", # 按月交易汇总
"/tranInfo/exportBillList", # 交易列表导出
"/sumbill/querySumBillInfoList", # 汇总账单列表
"/sumbill/queryAccDetail", # 账单明细
"/sumbill/exportSumBillInfoList", # 账单导出
"/settleInfo/querySettleRecord", # 结算记录
"/settleInfo/exportSettleRecord", # 结算记录导出
"/dwQuery/business/businessTradeSum", # 业务交易汇总
"/billDownload/summaryBill", # 账单打包下载
"/download/downLoadList", # 下载中心列表(两段式导出的第二段)
]
# ===============================================
BASE = "https://mch-web.tianquetech.com"
LOGIN_URL = BASE + "/login"
def log(msg):
line = f"[{datetime.now():%H:%M:%S}] {msg}"
print(line, flush=True)
return line
def keep_packet(url):
low = (url or "").lower()
if KEEP_KEYWORDS and not any(k.lower() in low for k in KEEP_KEYWORDS):
return False
return not any(k.lower() in low for k in SKIP_KEYWORDS)
def short_path(url):
"""去掉域名与查询串,方便聚合统计。"""
path = url.split("://", 1)[-1]
path = path[path.find("/"):] if "/" in path else path
return path.split("?", 1)[0]
def to_payload(data):
"""DrissionPage 的 postData 是 JSON 时会直接给 dict,这里统一回字符串。"""
if not data:
return ""
if isinstance(data, (dict, list)):
return json.dumps(data, ensure_ascii=False)
return str(data)
def resp_code(obj):
"""业务返回码:新接口用 code,老接口用 errorType/message。"""
if not isinstance(obj, dict):
return "", ""
code = obj.get("code")
msg = obj.get("msg") or obj.get("message") or ""
if code is None and obj.get("errorType"):
code, msg = obj.get("errorType"), obj.get("message") or ""
return ("" if code is None else str(code)), str(msg or "")
def data_keys(obj):
"""粗略描述响应结构,用于判断该接口能不能直接复用。"""
if not isinstance(obj, dict):
return ""
data = obj.get("data")
if isinstance(data, dict):
keys = list(data.keys())[:12]
for k, v in data.items():
if isinstance(v, list) and v and isinstance(v[0], dict):
return f"data{{{','.join(keys)}}} list[{k}]={list(v[0].keys())[:12]}"
return f"data{{{','.join(keys)}}}"
if isinstance(data, list):
return f"data[]={list(data[0].keys())[:12] if data and isinstance(data[0], dict) else type(data).__name__}"
return f"data={type(data).__name__}"
def guess_ext(content_type, url):
ct = (content_type or "").lower()
low = (url or "").lower()
if "spreadsheet" in ct or "excel" in ct or low.endswith((".xls", ".xlsx")):
return ".xlsx"
if "csv" in ct:
return ".csv"
if "zip" in ct:
return ".zip"
if "pdf" in ct:
return ".pdf"
if "octet-stream" in ct:
return ".bin"
return ".bin"
class Capture(object):
def __init__(self, root):
self.root = root
os.makedirs(root, exist_ok=True)
self.file_dir = os.path.join(root, "files")
os.makedirs(self.file_dir, exist_ok=True)
self.jsonl = open(os.path.join(root, "packets.jsonl"), "w", encoding="utf-8")
self.logf = open(os.path.join(root, "capture.log"), "w", encoding="utf-8")
self.apis = {}
self.seq = 0
def write_log(self, msg):
line = log(msg)
self.logf.write(line + "\n")
self.logf.flush()
def save_binary(self, path, data):
self.seq += 1
name = re.sub(r"[^0-9A-Za-z._-]", "_", path.strip("/").replace("/", "_"))[:80]
ext = guess_ext("", path)
fn = f"{self.seq:03d}_{name}{ext}"
with open(os.path.join(self.file_dir, fn), "wb") as f:
f.write(data)
return fn
def handle(self, pkt, route_label=""):
url = pkt.url or ""
if not keep_packet(url):
return
method = (pkt.method or "GET").upper()
path = short_path(url)
try:
body = pkt.response.body
except Exception as exc: # 下载/重定向类响应可能取不到 body
body = b""
err = str(exc)[:120]
else:
err = ""
content_type = ""
try:
content_type = (pkt.response.headers or {}).get("content-type", "")
except Exception:
pass
try:
status = pkt.response.status
except Exception:
status = ""
# DrissionPage 的 response.body 已经自动解析过:JSON 给 dict/list,二进制给 bytes,其它给 str
parsed, text, binary = None, "", ""
if isinstance(body, (dict, list)):
parsed = body
text = json.dumps(body, ensure_ascii=False)
elif isinstance(body, bytes):
binary = self.save_binary(path, body) if body else ""
elif body:
text = str(body)
if text.lstrip()[:1] in ("{", "["):
try:
parsed = json.loads(text)
except ValueError:
parsed = None
code, msg = resp_code(parsed)
size = len(body) if isinstance(body, bytes) else len(text.encode("utf-8"))
rec = {
"ts": datetime.now().isoformat(timespec="seconds"),
"route": route_label,
"method": method,
"url": url,
"path": path,
"query": dict(pkt.request.params or {}) if hasattr(pkt.request, "params") else {},
"postData": to_payload(pkt.request.postData)[:MAX_BODY_CHARS],
"status": status,
"contentType": content_type,
"code": code,
"msg": msg,
"size": size,
"dataKeys": data_keys(parsed),
"binaryFile": binary,
"body": "" if binary else text[:MAX_BODY_CHARS],
}
if err:
rec["bodyError"] = err
self.jsonl.write(json.dumps(rec, ensure_ascii=False) + "\n")
self.jsonl.flush()
item = self.apis.setdefault(path, {
"path": path,
"methods": [],
"count": 0,
"samplePostData": "",
"lastCode": "",
"lastMsg": "",
"dataKeys": "",
"contentType": "",
})
item["count"] += 1
if method not in item["methods"]:
item["methods"].append(method)
if rec["postData"] and not item["samplePostData"]:
item["samplePostData"] = rec["postData"]
item["lastCode"], item["lastMsg"] = code, msg
item["dataKeys"] = rec["dataKeys"] or item["dataKeys"]
item["contentType"] = content_type or item["contentType"]
noise = any(k.lower() in url.lower() for k in NOISE_KEYWORDS)
if not noise:
self.write_log(f"{method} {path} code={code or ('ok' if parsed is not None else '-')}"
f" {msg[:40]} {rec['size']}B" + (f" -> {binary}" if binary else ""))
return not noise
def summary(self):
out = os.path.join(self.root, "apis.json")
with open(out, "w", encoding="utf-8") as f:
json.dump({"capturedAt": datetime.now().isoformat(timespec="seconds"),
"apis": sorted(self.apis.values(), key=lambda x: (-x["count"], x["path"]))},
f, ensure_ascii=False, indent=2)
return out
def close(self):
self.jsonl.close()
self.logf.close()
def listen(page, cap, route_label, idle=IDLE_SECONDS, total=MAX_SECONDS):
"""监听直到接口空闲 idle 秒、或本轮总时长超 total;每来一个包就落盘。
注意:页面有 download/polling 之类的背景轮询会一直喂包,空闲判定实际靠 total 兜底。"""
start = time.time()
for pkt in page.listen.steps(timeout=idle):
if isinstance(pkt, list):
for p in pkt:
cap.handle(p, route_label)
else:
cap.handle(pkt, route_label)
if time.time() - start > total:
cap.write_log(f"达到本轮时长上限 {total}s,结束本轮监听")
return True
return False
def main():
from DrissionPage import ChromiumOptions, ChromiumPage
import tianque_login_drission as dl # 复用同目录的浏览器登录实现(含验证码 OCR)
if DO_LOGIN and not (dl.ACCOUNT and dl.PASSWORD):
log("请先在 tianque_login_test.py 顶部配置 ACCOUNT / PASSWORD")
return False
stamp = f"{datetime.now():%Y%m%d-%H%M%S}"
cap = Capture(os.path.join(CAPTURE_DIR, stamp))
cap.write_log(f"抓包目录:{cap.root} 模式:{MODE}")
opts = ChromiumOptions().set_argument("--start-maximized")
if HEADLESS:
opts.headless(True)
page = ChromiumPage(opts)
if DO_LOGIN:
page.get(LOGIN_URL)
time.sleep(2)
dl.js(page, "return sessionStorage.clear()")
page.refresh()
time.sleep(2)
if not dl.wait_ready(page):
cap.write_log("登录页 40 秒未渲染完成,退出")
return False
user = dl.browser_login(page)
if not user:
cap.write_log("浏览器登录失败,退出")
return False
cap.write_log(f"登录成功:mno={user.get('mno')} 商户={user.get('merchantName') or user.get('userName')}")
else:
page.get(LOGIN_URL)
time.sleep(2)
page.listen.start() # 全量监听,必须在触发页面前启动
cap.write_log("监听已启动")
try:
if MODE == "auto":
for label, route in REPORT_ROUTES:
cap.write_log(f"打开报表页:{label} {route}")
page.get(BASE + route)
time.sleep(PAGE_WAIT)
listen(page, cap, label, idle=8, total=PAGE_LISTEN) # 单页只收一轮,避免长页面互相拖住
cap.write_log("auto 模式走完,继续监听最后停留页的懒加载请求")
listen(page, cap, "tail", idle=IDLE_SECONDS, total=300)
else:
cap.write_log("manual 模式:请在浏览器里点开报表/账单菜单,脚本会实时记录接口")
cap.write_log("可对照这些接口找对应页面:")
for api in EXPECTED_APIS:
cap.write_log(f" {api}")
listen(page, cap, "manual")
except KeyboardInterrupt:
cap.write_log("手动中断(Ctrl+C),开始汇总已抓到的接口")
page.listen.stop()
out = cap.summary()
cap.write_log(f"接口清单已写:{out}")
if cap.apis:
cap.write_log(f"本次共捕获 {len(cap.apis)} 个接口:")
for item in sorted(cap.apis.values(), key=lambda x: (-x["count"], x["path"])):
cap.write_log(f" {item['count']:>3}x {item['path']} code={item['lastCode'] or '-'}"
f" {item['dataKeys'][:80]}")
else:
cap.write_log("没捕获到接口:确认页面真的发了请求,或放宽 KEEP_KEYWORDS")
cap.close()
log("浏览器保持打开,可直接对照页面核对")
return True
if __name__ == "__main__":
sys.exit(0 if main() else 1)