Files
37duAutomation/plugins/XQ0001-0100/XQ0076 交通银行数据导出/data/bank_login.py
T

441 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.
# -*- 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}