feat: 新增交通银行数据导出插件及测试通道机制

This commit is contained in:
2026-11-05 15:20:34 +08:00
parent 85051f979b
commit 4bac1248ad
230 changed files with 19827 additions and 1440 deletions
@@ -0,0 +1,139 @@
# -*- coding: utf-8 -*-
"""xq0076 数据层公共工具(按钮定位 / 登录页判定 / 点击等待)。
交行页面是 Ant Design,按钮文本常带中文空格("登 录" / "导 出" / "跳 过"),
且 xpath 中文匹配易翻车,统一改为「遍历 tag:button + 去空格文本比对」。
"""
import time
from .. import config
def norm(text):
"""去所有空白,便于「登 录」==「登录」比较。"""
return ''.join(str(text or '').split())
def is_login_page(page):
url = (getattr(page, 'url', '') or '').lower()
return config.LOGIN_HASH in url
def is_displayed(el):
"""真实可见性判断。
不能用 el.states.is_displayed 一个条件:交行把「图形验证码」放在
`<div style="display:none">` 里,DP 仍判 True,导致误报"检测到验证码"。
这里追加「渲染尺寸 > 0」校验(隐藏元素 rect 为 0 或取不到)。
"""
try:
if not el.states.is_displayed:
return False
except Exception:
return False
try:
w, h = el.rect.size
return w > 0 and h > 0
except Exception:
return False
def find_button(page, text, timeout=8, contains=False, only_enabled=True):
"""按去空格后的文本找按钮;找不到返回 None。
contains=True 时按包含匹配("同意" 命中 "我已阅读并同意")。
"""
target = norm(text)
deadline = time.time() + timeout
while True:
try:
for b in page.eles('tag:button'):
try:
if not is_displayed(b):
continue
label = norm(b.text)
hit = (target in label) if contains else (label == target)
if not hit:
continue
if only_enabled:
try:
if b.states.is_enabled is False:
continue
except Exception:
pass
return b
except Exception:
continue
except Exception:
pass
if time.time() >= deadline:
return None
time.sleep(0.5)
def click_button(page, text, timeout=8, contains=False):
btn = find_button(page, text, timeout=timeout, contains=contains)
if not btn:
return False
try:
btn.click()
return True
except Exception as e:
config.log(f'点击「{text}」失败:{e}', 'WARN')
return False
def scroll_to_bottom(page, settle=2.0, fast=False):
"""滚动到页面底部(政策页必须滚到底,同意按钮才可点)。
⚠️ 不用「瞬间 scrollTop = scrollHeight」:位置跳变太假,容易被风控识别。
默认走浏览器原生平滑滚动(behavior='smooth'),再停留 settle 秒,
观感与人工拖动一致;内部可滚动容器同样平滑滚动。
fast=True 时退回直接置底(仅用于非登录场景)。
"""
if fast:
try:
page.scroll.to_bottom()
except Exception:
pass
time.sleep(0.2)
return True
ok = False
try:
page.run_js("""
var behavior = 'smooth';
try { window.scrollTo({ top: document.body.scrollHeight, behavior: behavior }); }
catch (e) { window.scrollTo(0, document.body.scrollHeight); }
document.querySelectorAll('div, section, main, article').forEach(function (el) {
try {
if (el.scrollHeight > el.clientHeight + 40 && el.clientHeight > 120) {
el.scrollTo({ top: el.scrollHeight, behavior: behavior });
}
} catch (e) {}
});
""")
ok = True
except Exception:
try:
page.scroll.to_bottom()
ok = True
except Exception:
pass
if settle:
time.sleep(settle)
return ok
def wait_page_ready(page, keyword, timeout=20):
"""等页面出现关键文本(等 SPA 渲染完成)。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
body = page.run_js('return document.body ? document.body.innerText : ""') or ''
if keyword in body:
return True
except Exception:
pass
time.sleep(1)
return False
@@ -0,0 +1,525 @@
# -*- coding: utf-8 -*-
"""xq0076 交行接口通道(纯接口,借用页面国密库加密/签名)。
协议(2026-11 实测,密文与抓包逐字节一致):
请求 body = plainText=<hex( SM4-ECB( PKCS5(明文JSON), key ) )>
&verify=<hex( SM2.sign( UTF8(plainText的hex), privKey ) )>
响应 body = {"plainText": "<base64 密文>"} → base64→hex→SM4 解密→去 PKCS5→明文 JSON
鉴权 = Authorization: Bearer <JWT>(登录后由页面请求产生,hook 捕获)
加密/签名全部交给页面自带的 KeyouCryptography(window 上可见),不在 Python 侧重写国密,
平台升级加密实现时可自动跟随;只有换 key/私钥/签名规则才需要跟版。
"""
import json
import re
import time
from .. import config
# ==================== 会话密钥捕获(关键) ====================
# SM4 key 与 SM2 私钥都是「会话级」的:每次登录由服务端协商,与上一次不同。
# 之前把某一次的 key 硬编码进来,只在那个会话有效 —— 这是响应解不开的根因。
# 做法:页面加载前注入 hook,拦截页面自己的加解密调用,把当前会话的 key 抓下来。
JS_CAPTURE = r"""
(function () {
window.__sess = window.__sess || { sm4: '', sm2: '' };
function hook() {
try {
var K = window.KeyouCryptography;
if (!K || !K.algorithm || !K.algorithm.SM4) return false;
var SM4 = K.algorithm.SM4, SM2 = K.algorithm.SM2;
var U = K.util.UTF8, H = K.util.Hex;
if (!SM4.__hc) {
SM4.__hc = true;
var oe = SM4.encryptWithECB;
SM4.encryptWithECB = function (p, k) {
try { if (!window.__sess.sm4) window.__sess.sm4 = U.stringify(k); } catch (e) {}
return oe.apply(this, arguments);
};
var od = SM4.decryptWithECB;
SM4.decryptWithECB = function (d, k) {
try { if (!window.__sess.sm4) window.__sess.sm4 = U.stringify(k); } catch (e) {}
return od.apply(this, arguments);
};
}
if (SM2 && !SM2.__hc) {
SM2.__hc = true;
var os = SM2.sign;
SM2.sign = function (m, p) {
try { if (!window.__sess.sm2) window.__sess.sm2 = H.stringify(p); } catch (e) {}
return os.apply(this, arguments);
};
}
return true;
} catch (e) { return false; }
}
if (!hook()) {
var t = setInterval(function () { if (hook()) clearInterval(t); }, 200);
setTimeout(function () { clearInterval(t); }, 30000);
}
})();
"""
_captured = {'sm4': '', 'sm2': ''}
def install_capture(page):
"""注册初始化脚本:每次页面加载都会注入「会话密钥捕获 + 鉴权捕获」hook。"""
ok = False
try:
page.add_init_js(JS_CAPTURE)
ok = True
except Exception as e:
config.log(f'注册会话密钥捕获脚本失败:{e}', 'WARN')
try:
page.add_init_js(JS_HOOK_AUTH)
except Exception:
pass
return ok
def wait_session_keys(page, timeout=40, trigger=True):
"""捕获当前会话的 SM4/SM2 密钥。
两步保证:
① 现在页面里直接注入 hook(页面已加载时 add_init_js 不生效);
② 主动点一次页面「查询」,让页面自己走一遍「加密请求 → 解密响应」,hook 即拿到 key。
"""
try:
page.run_js(JS_CAPTURE)
except Exception as e:
config.debug(f'注入密钥 hook 失败:{e}')
if trigger:
try:
for el in page.eles('tag:button'):
try:
if el.states.is_displayed and ''.join((el.text or '').split()) == '查询':
el.click()
config.debug('已点页面「查询」触发密钥捕获')
break
except Exception:
continue
except Exception:
pass
deadline = time.time() + timeout
while time.time() < deadline:
try:
raw = page.run_js('return JSON.stringify(window.__sess || {})')
d = json.loads(raw) if raw else {}
except Exception:
d = {}
if d.get('sm4'):
_captured['sm4'] = d.get('sm4') or ''
_captured['sm2'] = d.get('sm2') or ''
config.log(f'已捕获会话密钥(SM4 {len(_captured["sm4"])} 字符'
f",SM2 {len(_captured['sm2'])} 字符)")
return dict(_captured)
time.sleep(2)
config.log('未捕获到会话密钥(回落到默认值,可能当前会话不匹配)', 'WARN')
return {}
# ==================== 页面注入:加密 + 签名 + 请求 + 解密 ====================
JS_TOOLKIT = r"""
if (!window.__bk) {
window.__bk = {
init: function () {
var K = window.KeyouCryptography;
if (!K) throw new Error('KeyouCryptography 未加载');
this.SM4 = K.algorithm.SM4;
this.SM2 = K.algorithm.SM2;
this.PAD = K.util.DataPadding;
this.H = K.util.Hex;
this.U = K.util.UTF8;
this.HP = K.util.Helper;
this.KEY = this.U.parse(arguments[0]);
this.PRIV = this.H.parse(arguments[1]);
return true;
},
_dec: function (bytes, mode) {
try {
var out;
if (mode === 'ECB') {
out = this.SM4.decryptWithECB(bytes, this.KEY);
} else if (mode === 'CBC_IV16') {
out = this.SM4.decryptWithCBC(bytes.slice(16), this.KEY, bytes.slice(0, 16));
} else {
var z = [];
for (var i = 0; i < 16; i++) z.push(0);
out = this.SM4.decryptWithCBC(bytes, this.KEY, z);
}
var s = this.U.stringify(this.PAD.decodeWithPKCS5(out, 16));
// 去掉首尾 BOM / 空白 / 控制字符(PKCS5 补位有时去不干净,尾部残留 \u0002)
var t = String(s)
.replace(/^[\s\u0000-\u001f\uFEFF]+/, '')
.replace(/[\s\u0000-\u001f\uFEFF]+$/, '');
if (t.charAt(0) === '{' || t.charAt(0) === '[') return t; // 必须是 JSON 才算成功
} catch (e) {}
return null;
},
_decodeResp: function (pt) {
// 密文格式可能是 base64 也可能是 hex;模式可能是 ECB 也可能 CBC,逐一尝试
var cands = [];
try {
var h1 = this.HP.b64tohex(pt);
if (h1) cands.push(h1);
} catch (e) {}
if (/^[0-9A-Fa-f]+$/.test(pt) && pt.length % 2 === 0) cands.push(pt);
var modes = ['ECB', 'CBC_IV16', 'CBC_ZERO'];
for (var i = 0; i < cands.length; i++) {
var bytes;
try { bytes = this.H.parse(cands[i]); } catch (e) { continue; }
for (var m = 0; m < modes.length; m++) {
var r = this._dec(bytes, modes[m]);
if (r !== null) {
window.__decMode = modes[m] + '/' + (i === 0 ? 'b64' : 'hex');
return r;
}
}
}
return null;
},
call: function (path, obj) {
var plain = JSON.stringify(obj);
var ct = this.SM4.encryptWithECB(this.PAD.encodeWithPKCS5(this.U.parse(plain), 16), this.KEY);
var ctHex = this.H.stringify(ct);
var sig = this.SM2.sign(this.U.parse(ctHex), this.PRIV);
var body = 'plainText=' + ctHex + '&verify=' + this.H.stringify(sig);
var xhr = new XMLHttpRequest();
xhr.open('POST', path, false);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Authorization', window.__auth || '');
xhr.setRequestHeader('SecurityType', 'S');
xhr.setRequestHeader('source', 'pc');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(body);
var raw = xhr.responseText || '';
var o = null;
try { o = JSON.parse(raw); } catch (e) { o = null; }
if (o && typeof o === 'object' && o.plainText) {
var dec = this._decodeResp(String(o.plainText));
if (dec !== null) return dec;
return 'ERR:decrypt-fail len=' + String(o.plainText).length +
' ct=' + (xhr.getResponseHeader('Content-Type') || '') +
' full=' + String(o.plainText).slice(0, 200);
}
if (o && typeof o === 'object') return raw; // 明文 JSON(如错误码)
return 'ERR:non-json status=' + xhr.status +
' ct=' + (xhr.getResponseHeader('Content-Type') || '') +
' len=' + raw.length + ' head=' + raw.slice(0, 80);
}
};
}
return window.__bk.init(arguments[0], arguments[1]);
"""
# 拦截页面所有请求的 Authorization(登录后页面自己发请求时会带上正式 JWT)
JS_HOOK_AUTH = r"""
if (!window.__authHook) {
window.__authHook = true;
window.__authList = window.__authList || [];
var sh = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function (k, v) {
try {
if (String(k).toLowerCase() === 'authorization' && v) {
window.__authList.push(String(v));
window.__auth = String(v);
}
} catch (e) {}
return sh.apply(this, arguments);
};
}
return true;
"""
JS_CALL = 'return window.__bk.call(arguments[0], arguments[1]);'
# ==================== 解密诊断(DEBUG 模式):hook 页面自身的解密调用 ====================
# 用途:我们手动加密的请求服务端能受理,但响应解不开;让页面自己发一次请求,
# 观察它到底调哪个 decrypt、用什么 key,从而确定正确的响应解密方式。
JS_DIAG_HOOK = r"""
window.__diag = [];
function __hookDec(obj, path) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) return;
var names = [];
try {
var cur = obj, d = 0;
while (cur && d < 3) {
Object.getOwnPropertyNames(cur).forEach(function (n) { if (names.indexOf(n) < 0) names.push(n); });
cur = Object.getPrototypeOf(cur); d++;
}
} catch (e) {}
names.forEach(function (n) {
if (!/decrypt|Decrypt|unseal|plainText|decodeResp/i.test(n)) return;
var f;
try { f = obj[n]; } catch (e) { return; }
if (typeof f !== 'function') return;
try {
obj[n] = function () {
var r = f.apply(this, arguments);
try {
var args = [];
for (var i = 0; i < arguments.length; i++) {
var a = arguments[i];
args.push((a && typeof a === 'object') ? JSON.stringify(a).slice(0, 160) : String(a).slice(0, 160));
}
window.__diag.push({ t: path + '.' + n, a: args, r: String(r).slice(0, 180) });
} catch (e) {}
return r;
};
} catch (e) {}
});
}
try {
Object.keys(window).forEach(function (k) {
try {
var v = window[k];
if (v && typeof v.getSessionData === 'function') __hookDec(v, 'win/' + k);
} catch (e) {}
});
} catch (e) {}
try { __hookDec(window.KeyouCryptography, 'Keyou'); } catch (e) {}
try { __hookDec(window.KeyouCryptography && window.KeyouCryptography.algorithm, 'Keyou.alg'); } catch (e) {}
try { __hookDec(window.CryptoJS, 'CryptoJS'); } catch (e) {}
return 'ok';
"""
def diagnose_init(page):
"""DEBUG 用:注入解密 hook(需在页面加载完成后调用)。"""
try:
page.run_js(JS_DIAG_HOOK)
return True
except Exception as e:
config.log(f'注入解密诊断 hook 失败:{e}', 'WARN')
return False
def diagnose_report(page, limit=3):
"""DEBUG 用:取回命中的解密调用。"""
try:
raw = page.run_js('return JSON.stringify((window.__diag || []).slice(0, 20))')
return json.loads(raw) if raw else []
except Exception:
return []
_last_call_ts = [0.0]
def _throttle():
gap = config.API_INTERVAL - (time.time() - _last_call_ts[0])
if gap > 0:
time.sleep(gap)
# ==================== 通道初始化 / 鉴权 ====================
def init(page, sm4_key=None, priv=None):
"""注入加密通道(需页面已加载出 KeyouCryptography)。
密钥优先用本次会话捕获到的值;捕获失败才回落到配置里的默认值。
"""
sm4 = sm4_key or _captured.get('sm4') or config.SM4_KEY
priv = priv or _captured.get('sm2') or config.SM2_PRIV
if not _captured.get('sm4'):
config.log('警告:使用默认密钥(可能与本会话不匹配,解密会失败)', 'WARN')
deadline = time.time() + 30
while time.time() < deadline:
try:
ok = page.run_js(JS_TOOLKIT, sm4, priv)
if ok:
config.log('国密通道已就绪')
return True
except Exception as e:
config.debug(f'注入通道失败:{e}')
time.sleep(1)
raise RuntimeError('页面国密库未加载(KeyouCryptography 不存在),无法初始化接口通道')
def install_auth_hook(page):
page.run_js(JS_HOOK_AUTH)
def _nudge(page):
"""轻推一下页面(切菜单触发一次带鉴权的请求),用于页面空闲没有请求时补抓 token。"""
try:
for el in page.eles('tag:li'):
try:
if '交易汇总' in (el.text or '') and el.states.is_displayed:
el.click()
config.debug('已切到「交易汇总」触发鉴权请求')
return True
except Exception:
continue
except Exception:
pass
return False
def wait_token(page, timeout=60):
"""等页面发出带正式 JWT 的请求(跳过 temporary 临时票据)。"""
start = time.time()
nudged = False
while time.time() - start < timeout:
# ① 优先用「最近一次页面请求实际带的」票据(hook 每次请求都会刷新)
try:
cur = page.run_js('return window.__auth || ""') or ''
except Exception:
cur = ''
if cur and 'temporary=' not in cur:
config.log(f'已捕获登录票据({len(cur)} 字符,取最近请求)')
return cur
# ② 历史列表兜底
try:
lst = page.run_js('return JSON.stringify(window.__authList || [])')
items = json.loads(lst) if lst else []
except Exception:
items = []
for item in reversed(items):
if item and 'temporary=' not in item:
config.log(f'已捕获登录票据({len(item)} 字符)')
# 必须写回 window.__auth:__bk.call 读的是它,登录过程中可能被临时票据覆盖
try:
page.run_js('window.__auth = arguments[0]; return true;', item)
except Exception as e:
config.debug(f'写回票据失败:{e}')
return item
# 15 秒还没抓到,主动切一次菜单触发请求
if not nudged and time.time() - start > 15:
nudged = True
_nudge(page)
time.sleep(2)
# 兜底:当前 __auth
cur = page.run_js('return window.__auth || ""') or ''
if cur and 'temporary=' not in cur:
return cur
raise RuntimeError('未捕获到登录票据(Authorization),可能登录未完成')
# ==================== 通用调用(限流 + 重试) ====================
def call(page, path, payload, retry=None):
"""调用一个业务接口,返回解密后的 dict。全局限流 + 重试。"""
retry = retry or config.RETRY_MAX
last_err = ''
for attempt in range(1, retry + 1):
_throttle()
try:
raw = page.run_js(JS_CALL, path, payload)
except Exception as e:
last_err = f'执行异常:{e}'
time.sleep(config.API_INTERVAL)
continue
_last_call_ts[0] = time.time()
if not raw:
last_err = '空响应'
continue
try:
data = json.loads(raw)
except Exception:
last_err = f'响应异常:{str(raw)[:220]}'
config.log(last_err, 'WARN')
time.sleep(config.API_INTERVAL)
continue
code = str(data.get('RespCode') or '')
msg = str(data.get('RespMsg') or '')
# 银行侧限流:退避后重试(不要立刻重发,否则一直被拒)
if code == 'AM00049' or '频繁' in msg:
last_err = f'RespCode={code} {msg}(退避 {config.RATE_LIMIT_WAIT}s)'
config.log(last_err, 'WARN')
time.sleep(config.RATE_LIMIT_WAIT)
continue
if code == '000000':
try:
mode = page.run_js('return window.__decMode || ""')
if mode:
config.debug(f'响应解密方式:{mode}')
except Exception:
pass
return data
last_err = f"RespCode={code} {data.get('RespMsg') or ''}"
# 业务错误(非系统异常)不重试
if code and code not in ('999999', 'AM00040'):
break
time.sleep(config.API_INTERVAL)
raise RuntimeError(f'接口 {path} 调用失败({attempt}/{retry}):{last_err}')
# ==================== 业务接口 ====================
def _fmt_start(d):
return d.strftime('%Y%m%d') + '000000'
def _fmt_end(d):
return d.strftime('%Y%m%d') + '235959'
def _base_payload(mcht_id, mcht_acc):
return {
'mchtId': mcht_id,
'shopId': '',
'mchtOrderNo': '',
'bussType': config.BUSS_TYPE_COUPON,
'tradeState': config.TRADE_STATE_ALL,
'tradeType': '',
'payType': '',
'authNo': '',
'tradeNo': '',
'paycardNo': '',
'mchtAcc': mcht_acc,
}
def query_trades(page, mcht_id, mcht_acc, date_from, date_to, page_index=1, page_size=None):
"""交易流水明细查询(商户验券)。"""
p = _base_payload(mcht_id, mcht_acc)
p.update({
'txnStartDate': _fmt_start(date_from),
'txnEndDate': _fmt_end(date_to),
'pageIndex': str(page_index),
'pageSize': str(page_size or config.PAGE_SIZE_QUERY),
})
return call(page, config.API_QUERY, p)
def submit_export(page, mcht_id, mcht_acc, date_from, date_to):
"""提交导出,返回 {taskID, filename}。"""
p = _base_payload(mcht_id, mcht_acc)
p.update({
'txnStartDate': _fmt_start(date_from),
'txnEndDate': _fmt_end(date_to),
'pageType': config.PAGE_TYPE,
})
data = call(page, config.API_EXPORT_SUBMIT, p)
rd = data.get('responseData') or {}
return {'task_id': rd.get('taskID') or '', 'filename': rd.get('filename') or ''}
def check_export(page, mcht_id, task_ids):
"""查导出任务状态,返回原始 responseData 列表。"""
data = call(page, config.API_EXPORT_STATUS, {
'mrchId': mcht_id,
'pageType': config.PAGE_TYPE,
'taskIdList': list(task_ids),
})
return data.get('responseData') or []
def get_download_url(page, mcht_id):
data = call(page, config.API_DOWNLOAD, {'mrchId': mcht_id, 'pageType': config.PAGE_TYPE})
return data.get('downLoadUrl') or ''
# ==================== 商户识别 ====================
def detect_merchant(page):
"""从页面文本解析 mchtId(15 位)与 mchtAcc(MER 账号)。"""
try:
txt = page.run_js('return document.body ? document.body.innerText : ""') or ''
except Exception:
txt = ''
mcht_id = ''
m = re.search(r'\b(\d{15})-[^\n]{2,40}', txt)
if m:
mcht_id = m.group(1)
accs = re.findall(r'\b(MER\d{6,})\b', txt)
mcht_acc = accs[0] if accs else ''
return mcht_id, mcht_acc
@@ -0,0 +1,421 @@
# -*- coding: utf-8 -*-
"""xq0076 交行「商户验券」交易流水导出。
双通道:
A. 接口(快,5 秒级):MSNGTQ/0002 查有无数据 → MSNGTO/0012 提交导出 →
0013 轮询 → downloadMchtFile 取 OSS 直链 → requests 下载。
B. UI 兜底(慢,约 1 分钟):接口任一步失败自动切换——
汇总页「商户验券」查看详情(业务类型/日期自动带过去)→ 流水页点「导 出」→
浏览器自己下载(页面自己完成加解密),再从磁盘取文件。
两条路都以「zip 内 csv 是否有数据行」作为最终判定,无数据不保留空文件。
"""
import os
import shutil
import time
import zipfile
import requests
import urllib3
from .. import config
from . import (click_button, find_button, is_displayed, wait_page_ready)
from . import bank_api
# 银行 OSS 域名用老 TLS,verify=False 下载;抑制无害的 InsecureRequestWarning 噪音
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
# ==================== 接口通道 ====================
def has_data_probe(page, mcht_id, mcht_acc, date_from, date_to):
"""查 1 条明细判断有无数据。返回 (是否有数据, 说明)。"""
data = bank_api.query_trades(page, mcht_id, mcht_acc, date_from, date_to,
page_index=1, page_size=1)
rows = data.get('responseData') or []
rd2 = data.get('responseData2') or {}
total = ''
if isinstance(rd2, dict):
total = rd2.get('totalRow') or ''
total = total or data.get('maxRow') or ''
if rows:
config.log(f'查询结果:有数据(总计 {total or "未知"} 条)')
return True, f'总计 {total or "未知"} 条'
config.log('查询结果:无数据,跳过导出')
return False, '无数据'
def _download(url, target_path, timeout=600):
"""下载 OSS 直链(无需 Cookie/Authorization)。"""
headers = {'User-Agent': UA, 'Referer': 'https://merchantapp.bankcomm.com/'}
tmp = target_path + '.part'
try:
with requests.get(url, headers=headers, timeout=timeout, verify=False, stream=True) as r:
r.raise_for_status()
with open(tmp, 'wb') as f:
for chunk in r.iter_content(1024 * 256):
if chunk:
f.write(chunk)
os.replace(tmp, target_path)
return os.path.getsize(target_path)
except Exception:
try:
if os.path.exists(tmp):
os.remove(tmp)
except Exception:
pass
raise
# ==================== UI 兜底通道 ====================
_JS_MARK = r"""
var t = arguments[0];
var p = document.querySelector('.ant-calendar-picker-container');
if (!p || !p.offsetWidth) return 'no-panel';
var tds = [].slice.call(p.querySelectorAll('td[title]'));
for (var i = 0; i < tds.length; i++) {
if ((tds[i].getAttribute('title') || '') === t) {
var old = document.getElementById('__pick_day__');
if (old) old.id = '';
tds[i].id = '__pick_day__';
return 'ok';
}
}
return 'not-found';
"""
_JS_STEP = r"""
var dir = arguments[0];
var p = document.querySelector('.ant-calendar-picker-container');
if (!p) return false;
var b = dir === 'next' ? p.querySelector('.ant-calendar-next-month-btn')
: p.querySelector('.ant-calendar-prev-month-btn');
if (b) { b.click(); return true; }
return false;
"""
def _pick_day(page, idx, day):
"""在日历面板上点选第 idx 个日期框(readonly 输入框只能面板点选)。"""
boxes = [e for e in page.eles('css:input.ant-calendar-picker-input') if is_displayed(e)]
if len(boxes) <= idx:
return False
try:
boxes[idx].click()
except Exception:
return False
time.sleep(1.0)
title = f'{day.year}年{day.month}月{day.day}日'
mark = page.run_js(_JS_MARK, title)
steps = 0
while mark == 'not-found' and steps < 24:
page.run_js(_JS_STEP, 'prev')
time.sleep(0.35)
steps += 1
mark = page.run_js(_JS_MARK, title)
while mark == 'not-found' and steps < 48:
page.run_js(_JS_STEP, 'next')
time.sleep(0.35)
steps += 1
mark = page.run_js(_JS_MARK, title)
if mark != 'ok':
config.log(f'日历面板找不到 {title}', 'WARN')
return False
el = page.ele('#__pick_day__', timeout=3)
if not el:
return False
el.click()
time.sleep(0.8)
try:
page.run_js("var e=document.getElementById('__pick_day__'); if(e) e.id='';")
except Exception:
pass
return True
def _csv_has_rows(zip_path):
"""检查 zip 内明细 csv 是否有数据行(>1 行 = 有数据)。"""
try:
with zipfile.ZipFile(zip_path) as zf:
for name in zf.namelist():
if not name.lower().endswith('.csv'):
continue
raw = zf.read(name)
try:
text = raw.decode('gbk', 'replace')
except Exception:
text = raw.decode('utf-8', 'replace')
lines = [ln for ln in text.splitlines() if ln.strip()]
config.debug(f'{name}: {len(lines)} 行')
if 'responseData' in name and len(lines) > 1:
return True, name, len(lines) - 1
except Exception as e:
config.log(f'检查 zip 内容失败:{e}', 'WARN')
return False, '', 0
def _select_all_stores(page):
"""汇总页「门店名称」多选里勾「全选」(不选的话汇总卡片没数据,查看详情不跳转)。"""
try:
multi = page.ele('css:.ant-select-selection--multiple', timeout=10)
except Exception:
multi = None
if not multi:
config.log('未找到门店多选框,跳过全选', 'WARN')
return False
try:
multi.click()
time.sleep(1.2)
hit = False
for wrap in page.eles('css:.ant-select-dropdown .ant-checkbox-wrapper'):
try:
if '全选' in ''.join((wrap.text or '').split()):
inp = wrap.ele('css:input.ant-checkbox-input')
try:
checked = bool(inp.states.is_checked)
except Exception:
checked = False
if not checked:
inp.click()
time.sleep(1)
config.log('已勾选「全选」门店')
hit = True
break
except Exception:
continue
# 收起下拉:只用 JS 在页面标题区触发 mousedown(antd 靠 document mousedown 关闭)。
# ⚠️ 不能用坐标点「空白处」——左侧菜单就在那里,会误点「退款审批」等菜单跳转。
try:
page.run_js("""
try {
var el = document.querySelector('.org_bottom_title')
|| document.querySelector('.ant-breadcrumb')
|| document.body;
el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
} catch (e) {}
""")
except Exception:
pass
time.sleep(1)
return hit
except Exception as e:
config.log(f'门店全选失败:{e}', 'WARN')
return False
def export_via_ui(page, date_from, date_to, save_dir, tag='商户验券'):
"""UI 兜底:汇总页商户验券「查看详情」→ 流水页「导 出」→ 浏览器下载。"""
config.log('改用页面 UI 导出(接口通道不可用)…')
dl_dir = config.get_download_dir()
os.makedirs(dl_dir, exist_ok=True)
try:
page.set.download_path(dl_dir)
page.set.when_download_file_exists('rename')
except Exception:
pass
# ① 交易汇总页
page.get(config.SITE_URL + '#/' + config.SUMMARY_HASH)
time.sleep(config.PAGE_SETTLE + 2)
if not wait_page_ready(page, '交易汇总', timeout=25):
config.log('汇总页未就绪,重试', 'WARN')
page.get(config.SITE_URL)
time.sleep(2)
page.get(config.SITE_URL + '#/' + config.SUMMARY_HASH)
time.sleep(config.PAGE_SETTLE + 2)
# ② 门店全选(不选则卡片无数据,查看详情不跳转)
_select_all_stores(page)
# ③ 自定义日期 + 面板选日期
if click_button(page, config.TXT_CUSTOM_DATE, timeout=8):
time.sleep(1.5)
_pick_day(page, 0, date_from)
_pick_day(page, 1, date_to)
# ④ 查询
click_button(page, config.TXT_QUERY_BTN, timeout=8)
time.sleep(config.UI_QUERY_WAIT)
# ④ 点「商户验券」卡片的查看详情(页面第 2 个)
# 等汇总卡片渲染稳定(加载完通常是 9 个「查看详情」,未加载完只有 3 个)
details = []
last = -1
stable = 0
deadline = time.time() + 30
while time.time() < deadline:
details = [b for b in page.eles('css:button.onClickShowDetail') if is_displayed(b)]
if len(details) == last and len(details) >= 2:
stable += 1
if stable >= 2:
break
else:
stable = 0
last = len(details)
time.sleep(1.5)
config.log(f'汇总页可见「查看详情」{len(details)} 个')
if len(details) < 2:
raise RuntimeError('汇总页未找到「商户验券」查看详情按钮(页面可能未加载完)')
details[1].click()
# 必须确认真的跳到交易流水页,否则会误点导出拿到「交易汇总.xlsx」
jumped = False
deadline = time.time() + 30
while time.time() < deadline:
if config.TRADE_HASH in (page.url or ''):
jumped = True
break
time.sleep(1)
if not jumped:
raise RuntimeError(f'点「商户验券-查看详情」未跳转到交易流水页(当前 {page.url}),已中止避免导错文件')
config.log(f'已进入交易流水页:{page.url}')
time.sleep(config.PAGE_SETTLE + 1)
# ⑤ 点导出,等浏览器下载
before = set(os.listdir(dl_dir))
btn = find_button(page, config.TXT_EXPORT_BTN, timeout=20)
if not btn:
raise RuntimeError('流水页找不到「导出」按钮')
btn.click()
config.log('已点击「导 出」,等待浏览器下载…')
path = None
deadline = time.time() + config.DOWNLOAD_TIMEOUT
while time.time() < deadline:
news = [n for n in os.listdir(dl_dir)
if n not in before and not n.endswith('.crdownload')]
if news:
candidate = os.path.join(dl_dir, news[-1])
size = os.path.getsize(candidate)
time.sleep(1.5)
if os.path.getsize(candidate) == size and size > 0:
path = candidate
break
time.sleep(1.5)
if not path:
raise RuntimeError(f'{config.DOWNLOAD_TIMEOUT}s 内未捕获到浏览器下载')
config.log(f'下载完成:{os.path.basename(path)}({os.path.getsize(path)} 字节)')
# ⑥ 检查有无数据 + 归档
has_rows, name, rows = _csv_has_rows(path)
if not has_rows:
config.log('导出文件无数据行,不保留文件', 'WARN')
try:
os.remove(path)
except Exception:
pass
return {'skipped': True, 'reason': '导出文件无数据行', 'note': '无数据'}
stamp = time.strftime('%Y%m%d_%H%M%S')
safe_range = f'{date_from.strftime("%Y%m%d")}-{date_to.strftime("%Y%m%d")}'
base = f'交通银行_{tag}_{safe_range}_{stamp}'
final_zip = os.path.join(save_dir, base + '.zip')
shutil.move(path, final_zip)
config.log(f'已归档:{final_zip}(明细 {rows} 行)')
csv_files = _unzip_csv(final_zip, save_dir, base)
return {'skipped': False, 'zip': final_zip, 'csv': csv_files,
'size': os.path.getsize(final_zip), 'rows': rows,
'range': f'{date_from} ~ {date_to}', 'via': 'ui'}
def _unzip_csv(zip_path, save_dir, base):
out = []
try:
with zipfile.ZipFile(zip_path) as zf:
for name in zf.namelist():
if not name.lower().endswith('.csv'):
continue
target = os.path.join(save_dir, f'{base}_{os.path.basename(name)}')
with zf.open(name) as src, open(target, 'wb') as dst:
shutil.copyfileobj(src, dst)
out.append(target)
if out:
config.log(f'已解压 {len(out)} 个 csv(GBK 编码,Excel 可直接打开)')
except Exception as e:
config.log(f'解压 csv 失败(zip 已保留):{e}', 'WARN')
return out
# ==================== 主流程(接口优先,失败自动回退 UI) ====================
def export_trade_flow(page, date_from, date_to, save_dir=None,
mcht_id='', mcht_acc='', tag='商户验券'):
save_dir = save_dir or config.default_output_dir()
os.makedirs(save_dir, exist_ok=True)
try:
bank_api.init(page)
if not (mcht_id and mcht_acc):
did, dacc = bank_api.detect_merchant(page)
mcht_id = mcht_id or did
mcht_acc = mcht_acc or dacc
if not (mcht_id and mcht_acc):
raise RuntimeError('未能识别商户号(mchtId/mchtAcc)')
config.log(f'商户:{mcht_id} / {mcht_acc}')
ok, note = has_data_probe(page, mcht_id, mcht_acc, date_from, date_to)
if not ok:
return {'skipped': True, 'reason': '查询无数据,未导出', 'note': note}
sub = bank_api.submit_export(page, mcht_id, mcht_acc, date_from, date_to)
task_id = sub.get('task_id')
if not task_id:
raise RuntimeError(f'提交导出未返回 taskID:{sub}')
config.log(f'已提交导出任务:{task_id}')
# taskstate 语义不稳定(实测 1=生成中、3=完成,不同批次可能不同),
# 所以只查一次记录状态,**以「能否下载到有效 zip」作为完成判据**,避免死等。
state = None
for i in range(1, config.POLL_MAX + 1):
try:
time.sleep(config.POLL_INTERVAL if i > 1 else 2)
items = bank_api.check_export(page, mcht_id, [task_id])
hit = next((it for it in items if str(it.get('taskID') or '') == task_id), None)
if hit is not None:
state = str(hit.get('taskstate'))
config.debug(f'轮询 {i}/{config.POLL_MAX}:taskstate={state}')
if state in config.EXPORT_STATE_DONE_SET:
break
except Exception as e:
config.debug(f'查任务状态失败(不影响下载):{e}')
break
config.log(f'导出任务状态:taskstate={state}')
stamp = time.strftime('%Y%m%d_%H%M%S')
safe_range = f'{date_from.strftime("%Y%m%d")}-{date_to.strftime("%Y%m%d")}'
base = f'交通银行_{tag}_{safe_range}_{stamp}'
final_zip = os.path.join(save_dir, base + '.zip')
# 文件未生成完时 OSS 上是 0 字节,需要重试下载
size = 0
for attempt in range(1, config.DOWNLOAD_RETRY + 1):
url = bank_api.get_download_url(page, mcht_id)
if not url:
time.sleep(config.POLL_INTERVAL)
continue
config.log(f'下载地址已获取:{url[-60:]}')
try:
size = _download(url, final_zip)
except Exception as e:
config.log(f'第 {attempt} 次下载失败:{e}', 'WARN')
size = 0
if size > 0 and zipfile.is_zipfile(final_zip):
break
config.log(f'文件尚未生成({size} 字节),{config.POLL_INTERVAL}s 后重试…', 'WARN')
time.sleep(config.POLL_INTERVAL)
if not size or not zipfile.is_zipfile(final_zip):
raise RuntimeError('导出文件未生成(下载得到空文件或非 zip),可稍后重试')
config.log(f'已下载:{final_zip}({size} 字节)')
has_rows, _, rows = _csv_has_rows(final_zip)
csv_files = _unzip_csv(final_zip, save_dir, base)
return {'skipped': False, 'zip': final_zip, 'csv': csv_files, 'size': size,
'task_id': task_id, 'state': state, 'rows': rows,
'range': f'{date_from} ~ {date_to}', 'via': 'api'}
except Exception as e:
config.log(f'接口通道失败({e}),自动回退页面 UI 导出', 'WARN')
return export_via_ui(page, date_from, date_to, save_dir, tag=tag)
@@ -0,0 +1,440 @@
# -*- coding: utf-8 -*-
"""xq0076 交行商户服务门户登录模块(账密自动登录,零接口复刻)。
站点登录链路(2026-11 实测,DOM 由业务侧提供确认):
1. 登录页填「手机号/BOC/MER账号」+「商服密码」(图形验证码默认隐藏,触发时才需人工);
2. 点「登 录」→ 弹出隐私政策**新标签页**:滚动到底 → 等倒计时结束 → 点「同意」;
3. 回到门户后出现 APP 扫码授权页 → 点「跳 过」→ 弹框「是否确定跳过?」→ 点「确 认」;
4. 进入 #/main(交易查询等菜单可用)。
注意:交行 token 存 sessionStorage,关闭浏览器即失效,所以每次运行都要走一遍上述流程;
「跳过扫码」只影响验券/收银功能,不影响报表导出。
"""
import random
import time
from DrissionPage import ChromiumPage, ChromiumOptions
from .. import config
from . import (click_button, find_button, is_displayed, is_login_page, norm,
scroll_to_bottom)
# 密码错误的页面提示关键词
_ERR_KEYWORDS = ('密码错误', '账号或密码', '账户或密码', '密码不正确', '账号不存在', '已被锁定')
def open_browser():
"""启动/复用可见浏览器(独立固定 profile)。
优先连接上次运行保留的浏览器实例(固定端口):交行 token 在 sessionStorage,
只要浏览器不关就能复用登录态,免去每次输账号密码。
"""
# ① 复用上次保留的浏览器
try:
page = ChromiumPage(f'127.0.0.1:{config.BROWSER_PORT}')
page.run_js('return 1')
config.log('复用上次保留的浏览器实例(登录态可能仍有效)')
return page
except Exception:
pass
co = ChromiumOptions()
if config.HEADLESS:
co.headless()
try:
co.set_local_port(config.BROWSER_PORT)
except Exception:
pass
co.set_argument('--start-maximized')
try:
co.set_pref('credentials_enable_service', False)
co.set_pref('profile.password_manager_enabled', False)
except Exception:
pass
co.set_user_data_path(config.get_browser_profile_dir())
try:
co.set_download_path(config.get_download_dir())
except Exception:
pass
page = ChromiumPage(co)
try:
page.set.download_path(config.get_download_dir())
page.set.when_download_file_exists('rename')
except Exception as e:
config.debug(f'设置下载目录失败(忽略):{e}')
if not config.HEADLESS:
config.apply_window_mode(page)
return page
# ==================== 登录态判定 ====================
def logged_in(page):
try:
url = (page.url or '')
except Exception:
return False
low = url.lower()
if config.LOGIN_HASH in low:
return False
if config.MAIN_HASH in low or 'MENU' in low:
return True
# 兜底:登录页的表单还在 → 未登录
try:
if page.ele(config.SEL_USERNAME, timeout=0.5):
return False
except Exception:
pass
return True
# ==================== 表单填写 ====================
def _fill_username(page, username):
box = page.ele(config.SEL_USERNAME, timeout=15)
if not box:
config.log('找不到账号输入框', 'ERROR')
return False
try:
cur = (box.value or '') if hasattr(box, 'value') else ''
except Exception:
cur = ''
if cur.strip() == username.strip():
config.log('账号已预填,跳过输入')
return True
box.clear()
box.input(username)
time.sleep(random.uniform(0.4, 0.9)) # 人工式停顿,避免瞬间填完
config.log('已填写账号')
return True
def _fill_password(page, password):
"""页面有多个 password 输入(登录 / 首次改密表单),只填可见的那个。"""
deadline = time.time() + 10
box = None
while time.time() < deadline and box is None:
for el in page.eles(config.SEL_PASSWORD):
if is_displayed(el):
box = el
break
if box is None:
time.sleep(0.5)
if box is None:
config.log('找不到密码输入框', 'ERROR')
return False
try:
box.clear()
box.input(password)
time.sleep(random.uniform(0.5, 1.1))
config.log('已填写密码')
return True
except Exception as e:
config.log(f'填写密码失败:{e}', 'ERROR')
return False
def _check_terms(page):
"""勾选「选择登录即代表激活账号,并同意《商户服务产品隐私权政策》」。
未勾选时点「登 录」页面不会提交(表现为"卡住"),必须先勾。
勾选框 id 固定为 #normal_login_remember。
"""
box = None
try:
box = page.ele('#normal_login_remember', timeout=5)
except Exception:
box = None
if box is None:
config.log('未找到隐私政策勾选框(页面可能改版)', 'WARN')
return False
try:
if box.states.is_checked:
config.debug('隐私政策已勾选')
return True
except Exception:
pass
try:
box.click()
time.sleep(random.uniform(0.8, 1.4))
if box.states.is_checked:
config.log('已勾选「同意隐私权政策」')
return True
# 兜底:点整行 label(勾选框可能被遮挡)
for wrapper in page.eles('css:.confirmRules .ant-checkbox-wrapper'):
try:
wrapper.click()
time.sleep(0.5)
if box.states.is_checked:
config.log('已勾选「同意隐私权政策」(label 兜底)')
return True
except Exception:
continue
except Exception as e:
config.log(f'勾选隐私政策失败:{e}', 'WARN')
config.log('隐私政策勾选框仍未选中,继续尝试登录', 'WARN')
return False
def _wait_captcha(page):
"""图形验证码默认隐藏;若被风控触发则暂停等人工输入。返回是否已就绪。"""
try:
cap = page.ele(config.SEL_CAPTCHA, timeout=1)
except Exception:
cap = None
if not cap or not is_displayed(cap):
return True
config.log('检测到图形验证码,请在浏览器窗口手动输入(脚本最多等 %ds)' % config.CAPTCHA_WAIT, 'WARN')
deadline = time.time() + config.CAPTCHA_WAIT
while time.time() < deadline:
try:
if (cap.value or '').strip():
config.log('验证码已输入,继续')
return True
except Exception:
pass
time.sleep(1)
config.log('等待验证码输入超时', 'ERROR')
return False
def _page_text(tab):
try:
return tab.run_js('return document.body ? document.body.innerText : ""') or ''
except Exception:
return ''
# ==================== 登录后流程(政策页 / 跳过扫码 / 弹框确认) ====================
def _all_tabs(page):
tabs = []
try:
for tid in page.tab_ids:
try:
tabs.append(page.get_tab(tid))
except Exception:
continue
except Exception:
tabs = [page]
if not tabs:
tabs = [page]
return tabs
def _find_agree_btn(tab):
"""在指定标签里找「同意」元素(排除「不同意」)。
交行政策页的同意不是 button,而是:
<div class="signBtnWrap">
<div class="disagree">不同意</div>
<div class="signBtn canSignBtn">同意</div>
</div>
所以选择器必须覆盖 div.signBtn / .canSignBtn。
"""
for sel in ('css:.signBtnWrap .signBtn', 'css:.signBtn', 'css:.canSignBtn',
'tag:button', 'tag:a', 'css:div[class*="agree"], div[class*="signBtn"]'):
try:
for el in tab.eles(sel):
try:
if not is_displayed(el):
continue
txt = norm(el.text)
if txt and '同意' in txt and '不同意' not in txt:
return el
except Exception:
continue
except Exception:
continue
return None
def _policy_agree_btn(tab):
"""政策页专用取按钮:只在「已解锁」时返回,未解锁返回 None(继续等)。
解锁标志 = class 里出现 canSignBtn(倒计时结束由页面自己加)。
"""
try:
has_wrap = bool(tab.eles('css:.signBtnWrap'))
except Exception:
has_wrap = False
if not has_wrap:
return _find_agree_btn(tab) # 不是该结构 → 通用兜底
for sel in ('css:.signBtnWrap .canSignBtn', 'css:.canSignBtn'):
try:
for el in tab.eles(sel):
try:
if is_displayed(el) and '同意' in norm(el.text):
return el
except Exception:
continue
except Exception:
continue
return None
def _is_policy_tab(tab):
"""判断某标签是不是隐私政策全文页(长文本 + 隐私/协议关键词)。
登录页虽然也含「隐私权政策」字样,但正文很短,用长度门槛区分。
"""
try:
body = _page_text(tab)
except Exception:
return False
if not body or len(body) < 600:
return False
return ('隐私' in body) or ('协议' in body) or ('条款' in body)
def _handle_policy(page, budget=25):
"""处理隐私政策全文页:滚到底 → 等倒计时 5 秒 → 点「同意」。
形态:勾选登录页「同意隐私权政策」后弹出新标签/新窗口(或当前页跳转)。
- 滚动走浏览器原生平滑滚动(瞬间跳底容易被风控识别);
- 每页只滚一次,滚完静置 POLICY_WAIT 秒等同意按钮解锁(实测约 5s)。
"""
end = time.time() + budget
scrolled = set()
while time.time() < end:
if logged_in(page):
return True
for tab in _all_tabs(page):
try:
if not _is_policy_tab(tab):
continue
tid = getattr(tab, 'tab_id', None)
except Exception:
continue
if tid not in scrolled:
time.sleep(config.POLICY_LOAD_WAIT) # 等页面加载稳定
scroll_to_bottom(tab, settle=2.0) # 人工式平滑滚动到底
time.sleep(config.POLICY_WAIT) # 等倒计时(约 5s)解锁按钮
scrolled.add(tid)
config.log(f'政策页已滚动到底,等待 {config.POLICY_WAIT}s 倒计时…')
btn = _policy_agree_btn(tab)
if btn is None:
config.debug('政策页「同意」尚未解锁(等 canSignBtn),继续等待')
continue
try:
btn.click()
config.log('已点击政策页「同意」')
time.sleep(1.5)
# 政策页通常自动关闭;若仍开着且不是主标签,手动关掉避免遮挡登录按钮
try:
if tab is not page and _is_policy_tab(tab):
tab.close()
config.debug('已关闭政策标签页')
except Exception:
pass
return True
except Exception as e:
config.debug(f'政策页同意按钮点击失败:{e}')
time.sleep(1)
return False
def _handle_skip_qr(page):
"""跳过 APP 扫码授权 + 二次确认弹框。返回是否点过。"""
if not click_button(page, config.TXT_SKIP_QR, timeout=1):
return False
config.log('已点击「跳过」扫码授权,等待确认弹框')
time.sleep(1)
for _ in range(10):
for el in page.eles('css:.ant-modal-confirm-btns button'):
try:
if is_displayed(el) and '确认' in ''.join((el.text or '').split()):
el.click()
config.log('已点「确认」跳过扫码')
time.sleep(1)
return True
except Exception:
continue
time.sleep(0.5)
return True
def _login_flow(page, agreed=False):
"""点登录后推进全流程,直到进入主界面。
政策页 / 跳过扫码 / 二次确认都是「出现了才处理」,都不阻塞主循环,
避免某个元素点不动时把整轮登录卡死。
"""
deadline = time.time() + config.LOGIN_WAIT
while time.time() < deadline:
if logged_in(page):
return True
# ① 隐私政策(弹窗或独立页)
if not agreed:
try:
if _handle_policy(page, budget=8):
agreed = True
continue
except Exception as e:
config.debug(f'处理政策异常:{e}')
# ② 跳过 APP 扫码授权 + 二次确认
try:
if _handle_skip_qr(page):
continue
except Exception as e:
config.debug(f'跳过扫码异常:{e}')
# ③ 错误提示(账号密码问题直接失败,避免空等)
body = _page_text(page)
for kw in _ERR_KEYWORDS:
if kw in body:
config.log(f'登录被拒:页面提示含「{kw}」', 'ERROR')
return False
time.sleep(1.5)
return logged_in(page)
# ==================== 主入口 ====================
def ensure_login(page, username=None, password=None, force=False):
"""确保页面处于已登录状态。返回 dict:{success, message, relogin}"""
page.get(config.SITE_URL)
time.sleep(2)
# 安装鉴权捕获 hook:登录成功后页面请求会带正式 JWT,供接口通道复用
try:
from . import bank_api
bank_api.install_auth_hook(page)
except Exception as e:
config.debug(f'安装鉴权 hook 失败:{e}')
if not force and logged_in(page):
config.log('浏览器残留登录态仍有效,直接复用')
return {'success': True, 'message': '复用残留登录态', 'relogin': False}
if not username or not password:
msg = '登录账号/密码缺失:请在插件界面填写并保存配置'
config.log(msg, 'ERROR')
return {'success': False, 'message': msg, 'relogin': False}
config.log('开始账密登录…')
page.get(config.LOGIN_URL)
if not _fill_username(page, username):
return {'success': False, 'message': '找不到账号输入框', 'relogin': True}
if not _fill_password(page, password):
return {'success': False, 'message': '找不到密码输入框', 'relogin': True}
if not _wait_captcha(page):
return {'success': False, 'message': '图形验证码未输入', 'relogin': True}
# 必须先勾选「同意隐私权政策」,否则点登录不提交(表现为卡住)
_check_terms(page)
# 勾选后会弹出隐私政策全文页(新标签/新窗口):滚到底 + 点「同意」,
# 否则登录按钮会被遮挡,点下去等于点空
# 预算 8s:勾选后政策页通常立即弹出;没弹就直接点登录,交给 _login_flow 兜底,
# 避免每次白等 20 秒
policy_ok = _handle_policy(page, budget=8)
if not click_button(page, config.TXT_LOGIN_BTN, timeout=8):
return {'success': False, 'message': '找不到登录按钮', 'relogin': True}
config.log('已提交登录,处理政策页 / 扫码授权…')
if _login_flow(page, agreed=policy_ok):
config.log(f'登录成功:{page.url}')
return {'success': True, 'message': '登录成功', 'relogin': True}
return {'success': False, 'message': '登录未完成(政策页未同意 / 账号密码有误 / 超时)', 'relogin': True}