feat: 新增交通银行数据导出插件及测试通道机制
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""打开 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()
|
||||
@@ -0,0 +1,228 @@
|
||||
"""lotsmall(user.lotsmall.cn)登录联调脚本。
|
||||
|
||||
用法:
|
||||
1. 在下面「配置区」填 ACCOUNT / PASSWORD
|
||||
2. 运行:d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/lotsmall_probe/lotsmall_login_test.py
|
||||
|
||||
流程:submitToken → 图片验证码(ddddocr)→ RSA 加密密码 → 登录;
|
||||
验证码失败时可用同站滑块接口换取的凭证兜底(登录接口同样认可)。
|
||||
密码错误不重试,避免触发平台锁号。
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import urllib.parse
|
||||
from datetime import datetime
|
||||
|
||||
import requests
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
|
||||
# ==================== 配置区 ====================
|
||||
ACCOUNT = "" # 用户名(手机号或用户名)
|
||||
PASSWORD = "" # 密码
|
||||
MODE = "auto" # auto=先图片验证码,失败再走滑块;ocr=只走图片验证码;slider=只走滑块
|
||||
MAX_ATTEMPTS = 3 # 验证码级失败的最大轮次(密码错误立即停止)
|
||||
SAVE_TOKEN = True # 登录成功后把 token 落到临时文件,便于后续接口联调
|
||||
VERIFY_TOKEN = True # 登录成功后调用一次 userInfo 验证 token 是否可用
|
||||
# ===============================================
|
||||
|
||||
# 账号密码也可以写在同目录 account.json({"account": "...", "password": "..."})
|
||||
_ACC_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "account.json")
|
||||
if os.path.exists(_ACC_FILE):
|
||||
_acc = json.load(open(_ACC_FILE, encoding="utf-8"))
|
||||
ACCOUNT = ACCOUNT or _acc.get("account", "")
|
||||
PASSWORD = PASSWORD or _acc.get("password", "")
|
||||
|
||||
BASE = "https://user.lotsmall.cn"
|
||||
TIMEOUT = 15
|
||||
RSA_PUBLIC_KEY = (
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI5kmdW9rmxQlTraZ6Wx+C7kYRDjL332N53dsqFsqq"
|
||||
"T+PX6mosaM5hW4MS4vUbQNtUblhmQgzmUD0KBJFH9YZMmSPLdCC+G4r7d2PPFBrCy+9dFUMUNaT4Penya"
|
||||
"VQJyAp3bhUJ7n93bRJT9jtxsdDwJ/Zl12A/kO93fr7+waaepwIDAQAB"
|
||||
)
|
||||
TOKEN_FILE = os.path.join(os.environ.get("TEMP", "."), "lotsmall_token.json")
|
||||
|
||||
CODE_CAPTCHA_ERROR = 1005006903 # 错误的验证码
|
||||
CODE_PASSWORD_ERROR = 1005006202 # 用户名或密码错误
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(f"[{datetime.now():%H:%M:%S}] {msg}", flush=True)
|
||||
|
||||
|
||||
def new_session():
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"Content-Type": "application/json;charset=UTF-8",
|
||||
"Origin": BASE,
|
||||
"Referer": BASE + "/usercenter/login",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36",
|
||||
})
|
||||
return s
|
||||
|
||||
|
||||
def post_json(session, path, payload=None):
|
||||
r = session.post(BASE + path, json=payload or {}, timeout=TIMEOUT)
|
||||
try:
|
||||
return r.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"{path} 返回非 JSON(HTTP {r.status_code}):{r.text[:200]}")
|
||||
|
||||
|
||||
def get_submit_token(session):
|
||||
data = post_json(session, "/corp-user/baseSupportService/submitToken")
|
||||
if data.get("code") != 200 or not data.get("data"):
|
||||
raise RuntimeError(f"获取 submitToken 失败:{data}")
|
||||
return data["data"]
|
||||
|
||||
|
||||
def fetch_img_code(session, submit_token):
|
||||
# 注意:该接口 body 必须是裸字符串 token,不能传 JSON 对象,
|
||||
# 否则图片能返回但验证码会绑到错误 key,登录永远报「错误的验证码」
|
||||
r = session.post(BASE + "/corp-user/baseSupportService/imgCode", data=submit_token,
|
||||
headers={"Content-Type": "application/json;charset=UTF-8"}, timeout=TIMEOUT)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"获取图片验证码返回非 JSON(HTTP {r.status_code}):{r.text[:200]}")
|
||||
if data.get("code") != 200 or not data.get("data"):
|
||||
raise RuntimeError(f"获取图片验证码失败:{data}")
|
||||
b64 = data["data"].split(",", 1)[1] if "," in data["data"][:100] else data["data"]
|
||||
return base64.b64decode(b64)
|
||||
|
||||
|
||||
def ocr_code(png_bytes):
|
||||
try:
|
||||
import ddddocr
|
||||
except ImportError:
|
||||
raise RuntimeError("未安装 ddddocr,请先 pip install ddddocr")
|
||||
code = ddddocr.DdddOcr(show_ad=False).classification(png_bytes).strip()
|
||||
return code if len(code) == 5 else ""
|
||||
|
||||
|
||||
def _decode_image(b64):
|
||||
import cv2
|
||||
import numpy as np
|
||||
return cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
|
||||
|
||||
def solve_slider(session, submit_token):
|
||||
"""用同站滑块接口换取登录接口认可的 verificationCode(页面未启用,实测可用)。"""
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
r = session.get(f"{BASE}/corp-user-http/api/slider/validate",
|
||||
params={"no": "sduser", "submitToken": submit_token}, timeout=TIMEOUT)
|
||||
data = (r.json() or {}).get("data") or {}
|
||||
if not data.get("oriImg"):
|
||||
return ""
|
||||
|
||||
bg = _decode_image(data["oriImg"])
|
||||
piece = _decode_image(data["newImg"])
|
||||
alpha = piece[:, :, 3]
|
||||
ys, xs = np.where(alpha > 10)
|
||||
tpl = piece[ys.min():ys.max() + 1, xs.min():xs.max() + 1, :3]
|
||||
mask = piece[ys.min():ys.max() + 1, xs.min():xs.max() + 1, 3]
|
||||
res = cv2.matchTemplate(bg[:, :, :3], tpl, cv2.TM_CCOEFF_NORMED, mask=mask)
|
||||
_, score, _, loc = cv2.minMaxLoc(res)
|
||||
|
||||
for dx in (0, -1, 1, -2, 2):
|
||||
resp = session.post(f"{BASE}/corp-user-http/api/slider/validate",
|
||||
data={"no": "sduser", "submitToken": submit_token, "X": loc[0] + dx},
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
timeout=TIMEOUT).json()
|
||||
if resp.get("code") == 200 and resp.get("data"):
|
||||
log(f"滑块通过(score={score:.3f}, X={loc[0] + dx})")
|
||||
return str(resp["data"])
|
||||
return ""
|
||||
|
||||
|
||||
def rsa_encrypt(text):
|
||||
pem = "-----BEGIN PUBLIC KEY-----\n" + RSA_PUBLIC_KEY + "\n-----END PUBLIC KEY-----"
|
||||
key = serialization.load_pem_public_key(pem.encode())
|
||||
cipher = key.encrypt(text.encode(), padding.PKCS1v15())
|
||||
return urllib.parse.quote(base64.b64encode(cipher).decode(), safe="")
|
||||
|
||||
|
||||
def do_login(session, submit_token, code):
|
||||
payload = {
|
||||
"account": ACCOUNT.strip(),
|
||||
"type": 1,
|
||||
"credentials": rsa_encrypt(PASSWORD.strip()),
|
||||
"verificationCode": code,
|
||||
"submitToken": submit_token,
|
||||
"encrypted": "T",
|
||||
}
|
||||
return post_json(session, "/corp-user/loginService/login", payload)
|
||||
|
||||
|
||||
def verify_token(session, access_token):
|
||||
r = session.post(BASE + "/corp-user/userService/userInfo", json={},
|
||||
headers={"cu-token": access_token}, timeout=TIMEOUT)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
return f"非 JSON 响应(HTTP {r.status_code})"
|
||||
return f"code={data.get('code')} message={data.get('message')}"
|
||||
|
||||
|
||||
def main():
|
||||
if not ACCOUNT or not PASSWORD:
|
||||
log("请先在脚本顶部配置区填写 ACCOUNT / PASSWORD")
|
||||
return False
|
||||
|
||||
session = new_session()
|
||||
slider_ok = MODE in ("auto", "slider")
|
||||
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
log(f"===== 第 {attempt}/{MAX_ATTEMPTS} 轮 =====")
|
||||
code, submit_token = "", ""
|
||||
|
||||
if MODE in ("auto", "ocr"):
|
||||
submit_token = get_submit_token(session)
|
||||
png = fetch_img_code(session, submit_token)
|
||||
code = ocr_code(png)
|
||||
log(f"图片验证码 OCR:{code or '识别失败'}")
|
||||
|
||||
if not code and slider_ok:
|
||||
submit_token = get_submit_token(session)
|
||||
code = solve_slider(session, submit_token)
|
||||
|
||||
if not code:
|
||||
log("本轮未得到可用验证码,重试")
|
||||
continue
|
||||
|
||||
resp = do_login(session, submit_token, code)
|
||||
log(f"登录返回:code={resp.get('code')} message={resp.get('message')}")
|
||||
|
||||
if resp.get("code") == 200 and resp.get("data"):
|
||||
data = resp["data"]
|
||||
token = data.get("accessToken") or ""
|
||||
log(f"登录成功,accessToken={token[:24]}...")
|
||||
if VERIFY_TOKEN and token:
|
||||
log("token 校验:" + verify_token(session, token))
|
||||
if SAVE_TOKEN:
|
||||
with open(TOKEN_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
log(f"token 已保存:{TOKEN_FILE}")
|
||||
return True
|
||||
|
||||
if resp.get("code") == CODE_PASSWORD_ERROR:
|
||||
log("账号或密码错误,停止重试(避免锁号)")
|
||||
return False
|
||||
|
||||
if resp.get("code") == CODE_CAPTCHA_ERROR:
|
||||
log("验证码未通过,继续下一轮")
|
||||
continue
|
||||
|
||||
log("出现未预期错误,停止重试")
|
||||
return False
|
||||
|
||||
log("已达最大轮次,登录失败")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(0 if main() else 1)
|
||||
@@ -0,0 +1,152 @@
|
||||
"""检票员报表全自动导出(纯接口版)。
|
||||
|
||||
流程:登录 lotsmall -> statisticsSupport 取 authCode/sign/appId/userCode
|
||||
-> verifySaasAuthCode 换 JWT -> preview 取报表元数据
|
||||
-> searchFilter 查询 -> total>0 才 newExport 下载 xlsx(查询无数据直接跳过)
|
||||
|
||||
账号密码写在同目录 account.json:{"account": "...", "password": "..."}
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import requests
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import lotsmall_login_test as login_mod # noqa: E402
|
||||
|
||||
TOKEN_FILE = os.path.join(os.environ["TEMP"], "lotsmall_token.json")
|
||||
OUT_DIR = os.path.join(os.environ["TEMP"], "lotsmall_export")
|
||||
REPORT_ID = 3066
|
||||
REPORT_URL = f"https://platform-report-sh1.zhiyoubao.com/reportView?id={REPORT_ID}"
|
||||
BEGIN = "2026-11-01 00:00:00"
|
||||
END = "2026-11-05 23:59:59"
|
||||
|
||||
ADMIN = "https://www.lotsmall.cn"
|
||||
RPT = "https://platform-report-sh1.zhiyoubao.com"
|
||||
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36"
|
||||
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
|
||||
|
||||
def load_token():
|
||||
try:
|
||||
return json.load(open(TOKEN_FILE, encoding="utf-8")).get("accessToken") or ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def admin_session(token):
|
||||
s = requests.Session()
|
||||
s.headers.update({"tyAuthToken": token, "User-Agent": UA, "Referer": ADMIN + "/manage/"})
|
||||
return s
|
||||
|
||||
|
||||
def fetch_report_params(token):
|
||||
"""statisticsSupport 拿报表接入参数;token 失效时返回 None。"""
|
||||
ts = int(time.time() * 1000)
|
||||
url = (f"{ADMIN}/statistics/webApi/statisticsSupport/"
|
||||
f"?timestamp={ts}&reportId={REPORT_ID}&reportUrl={REPORT_URL}&terminalTpe=0")
|
||||
r = admin_session(token).get(url, timeout=20)
|
||||
try:
|
||||
j = r.json()
|
||||
except ValueError:
|
||||
return None
|
||||
if j.get("code") != 200 or not j.get("data"):
|
||||
print("statisticsSupport 失败:", r.text[:200])
|
||||
return None
|
||||
return j["data"]
|
||||
|
||||
|
||||
def ensure_token():
|
||||
token = load_token()
|
||||
if token:
|
||||
info = fetch_report_params(token)
|
||||
if info:
|
||||
return token, info
|
||||
print("token 已过期,重新登录...")
|
||||
if not login_mod.main():
|
||||
raise SystemExit("登录失败,请检查 account.json 里的账号密码")
|
||||
token = load_token()
|
||||
info = fetch_report_params(token)
|
||||
if not info:
|
||||
raise SystemExit("登录后仍取不到报表接入参数")
|
||||
return token, info
|
||||
|
||||
|
||||
def main():
|
||||
token, info = ensure_token()
|
||||
auth_code = info["authCode"]
|
||||
app_id = info.get("appId", "xj")
|
||||
sign = info["sign"]
|
||||
rpt_ts = info["timestamp"]
|
||||
user_code = info.get("bigDataLoginAuthCode")
|
||||
corp_code = info.get("corpCode")
|
||||
print(f"authCode={auth_code} appId={app_id} sign={sign} userCode={user_code} corpCode={corp_code}")
|
||||
|
||||
rs = requests.Session()
|
||||
rs.headers.update({"User-Agent": UA, "Origin": RPT})
|
||||
|
||||
rv = rs.get(f"{RPT}/api/partner/auth/verifySaasAuthCode",
|
||||
params={"authCode": auth_code, "appId": app_id}, timeout=20)
|
||||
print("verifySaasAuthCode:", rv.status_code, rv.text[:200])
|
||||
jwt = ((rv.json().get("result") or {}).get("token")
|
||||
or (rv.json().get("result") or {}).get("accessToken")
|
||||
or (rv.json().get("data") or {}).get("token"))
|
||||
if not jwt:
|
||||
raise SystemExit("未取到 JWT,结构:" + rv.text[:500])
|
||||
|
||||
hdr = {
|
||||
"authCode": auth_code, "appId": app_id, "timestamp": str(rpt_ts), "sign": sign,
|
||||
"Authorization": jwt, "Content-Type": "application/json",
|
||||
"Origin": RPT, "Referer": RPT + "/",
|
||||
}
|
||||
q = {"authCode": auth_code, "appId": app_id, "sign": sign, "timestamp": rpt_ts,
|
||||
"userCode": user_code, "corpCode": corp_code, "terminalTpe": 0}
|
||||
|
||||
pv = rs.get(f"{RPT}/api/report/preview/{REPORT_ID}", params=q, headers=hdr, timeout=20)
|
||||
print("preview:", pv.status_code, pv.text[:200])
|
||||
meta = pv.json().get("result") or {}
|
||||
detail_id = meta.get("reportDetailId") or meta.get("id") or 3275
|
||||
columns = meta.get("reportColumnList") or []
|
||||
|
||||
body = {
|
||||
"shareMode": 0, "reportType": 0, "id": detail_id,
|
||||
"params": {
|
||||
"terminalTpe": "0", "merchant_id": "23985", "userInfoId": "59567",
|
||||
"corpCode": corp_code, "appId": app_id,
|
||||
"userCode": user_code, "subAccountId": "59925", "roleType": "4",
|
||||
"pageIndex": 1, "pageSize": 50,
|
||||
"beginTradeDate": BEGIN, "endTradeDate": END,
|
||||
"id": str(REPORT_ID),
|
||||
},
|
||||
"reportColumnDisplayList": columns,
|
||||
}
|
||||
resp = rs.post(f"{RPT}/api/report/searchFilter", headers=hdr, json=body, timeout=30)
|
||||
print("searchFilter:", resp.status_code, resp.text[:200])
|
||||
rsl = (resp.json().get("result") or {}).get("reportSearchList") or [{}]
|
||||
total = rsl[0].get("total")
|
||||
print("total =", total, "rows =", len(rsl[0].get("rows") or []))
|
||||
|
||||
if not total:
|
||||
print("查询无数据,跳过导出")
|
||||
return True
|
||||
|
||||
body["reportColumnFilterList"] = [{"reportDetailId": detail_id}]
|
||||
ex = rs.post(f"{RPT}/api/report/newExport", headers=hdr, json=body, timeout=120)
|
||||
print("newExport:", ex.status_code, ex.headers.get("content-disposition"), len(ex.content))
|
||||
if ex.content[:2] != b"PK":
|
||||
print("导出返回非 xlsx:", ex.text[:300])
|
||||
return False
|
||||
out = os.path.join(OUT_DIR, f"检票员检票报表_{int(time.time())}.xlsx")
|
||||
open(out, "wb").write(ex.content)
|
||||
print("已保存:", out)
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(0 if main() else 1)
|
||||
Reference in New Issue
Block a user