Files
37duAutomation/plugins/xq0008/logic/web_login.py
T
puddy 843ff244a6 feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
2026-10-26 15:42:50 +08:00

484 lines
18 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 -*-
"""重庆人社网上服务大厅(政务平台)法人登录模块 —— XQ0014 专用(不共享登录态)。
每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务。
不做 cookies 缓存:政务平台 cookies 极易失效,缓存无意义;统一每次现场真登录
(浏览器走完整 SSO 流程 + ddddocr 识别图形验证码)。
登录流程:
1. 打开办事大厅页面 → 等待登录入口出现;
2. 点击「登录」→ 跳转新 tab 到 SSO(authcq.cqdcg.com:1443/sso/login);
3. 切换「法人用户」tab;
4. 输入账号(统一社会信用代码或政务平台用户名)+ 密码;
5. 元素截图截取图形验证码(base64 内嵌 PNG)→ ddddocr 识别 → 输入验证码;
6. 点击「登 录」→ 等待跳回办事大厅域名即成功;
7. 识别失败自动刷新验证码重试(验证码 5 次/轮 × 流程 3 轮)。
"""
import os
import time
import random
import base64
from .. import config
APPLY_URL = 'https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/arrondi/ApplyOnline'
SSO_KEYWORD = 'authcq.cqdcg.com:1443/sso/login'
HOME_KEYWORD = 'ggfw.rlsbj.cq.gov.cn'
WORK_KEYWORD = 'onlineoffice/index' # 登录成功后新开的工作台 tab
RETRY_MAX = 5 # 验证码最大重试次数(每轮)
FLOW_RETRY = 3 # 整个登录流程最大轮数
TIMEOUT = 10 # 元素等待超时(秒)
HEADLESS = False
HUMAN_DELAY = (0.4, 1.2) # 操作间随机延时区间(秒),模拟人工降低脚本特征
def _captcha_debug_dir():
"""验证码调试图片目录(仅调试模式开启时落盘)。"""
return os.path.join(config.CKPT_DIR, 'debug_captcha')
# ================== 验证码识别(元素截图 + ddddocr) ==================
def _recognize_captcha(img_bytes):
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景的导入开销。"""
import ddddocr
ocr = ddddocr.DdddOcr(show_ad=False)
return ocr.classification(img_bytes).strip()
def _dump_debug_captcha(img_bytes, text):
"""可选:落盘验证码调试图片(仅调试模式开启时),便于分析识别失败样本。"""
if not config.is_debug():
return
try:
d = _captcha_debug_dir()
os.makedirs(d, exist_ok=True)
path = os.path.join(d, f"captcha_{int(time.time() * 1000)}_{text or 'unknown'}.png")
with open(path, 'wb') as f:
f.write(img_bytes)
except Exception as e:
config.log(f"保存调试图片失败:{e}", "WARN")
def _find_input(tab, selectors):
"""按候选选择器顺序查找输入框。"""
for sel in selectors:
ele = tab.ele(sel, timeout=2)
if ele:
return ele
return None
def _find_captcha(tab):
"""定位验证码图片 + 输入框。
从验证码输入框的容器往上找(DOM 结构:div.normalCode > span包input + img.code),
避免命中页面其它 base64 图标(实测:img[src^=data:image] 会抓到 icon)。
"""
code_input = tab.ele('css:input[placeholder*="图形验证码"]', timeout=TIMEOUT)
img = None
if code_input:
holder = code_input.parent(2) # div.normalCode 容器
if holder:
img = holder.ele('tag:img', timeout=1)
if img is None:
img = tab.ele('css:.ant-tabs-tabpane-active img[src^="data:image"]', timeout=2)
return img, code_input
def _read_img_bytes(img):
"""验证码图转 bytes:优先直接解码 base64 src(像素无损、无 DPR 缩放),失败退回元素截图。"""
try:
src = img.attr('src') or ''
if 'base64,' in src:
return base64.b64decode(src.split('base64,', 1)[1])
except Exception:
pass
return img.get_screenshot(as_bytes='png')
# ================== 登录主流程 ==================
def _human_pause(a=None, b=None):
"""操作间随机延时,模拟人工节奏。"""
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
time.sleep(random.uniform(lo, hi))
def _dismiss_notice(page):
"""关闭首页/工作台弹窗(「温馨提示」我知道了、授权提示同意等),避免遮挡操作。"""
candidates = [
'tag:button@@text()=我知道了',
'tag:button@@text()=知道了',
'tag:button@@text()=同意',
'tag:button@@text()=确定',
]
for _ in range(3):
btn = None
for sel in candidates:
try:
btn = page.ele(sel, timeout=1)
except Exception:
btn = None
if btn:
break
if not btn:
return
try:
btn.click()
config.log(f"已关闭弹窗(点击:{btn.text.strip()})")
time.sleep(0.5)
except Exception:
time.sleep(0.5)
def _sso_form_ready(t):
"""判断某 tab 是否已是渲染完成的 SSO 登录页:URL 在 SSO 且「法人用户」tab 已出现。
注意用 text()= 精确匹配——text(): 模糊匹配会命中包含该文字的外层容器 div。"""
try:
if SSO_KEYWORD not in t.url:
return False
return bool(t.ele('tag:div@@text()=法人用户', timeout=0.5))
except Exception:
return False
def _wait_sso_ready(tab):
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作。"""
last_url = None
for _ in range(60): # 最多等 30 秒
try:
url = tab.url
except Exception:
return False
stable = (url == last_url)
last_url = url
if _sso_form_ready(tab) and stable:
break
time.sleep(0.5)
time.sleep(1.5) # 再缓冲,确保 React 渲染完成
return True
def _is_work_tab(t):
"""是否登录完成的工作台页(onlineoffice/index)。
必须 origin 前缀匹配 + 路径含 onlineoffice/index——跳转链中间页的 redirectUrl 参数也含
ggfw/onlinehall 字样,用包含匹配会误判。"""
try:
u = (t.url or '').strip()
except Exception:
return False
return u.startswith('https://' + HOME_KEYWORD) and WORK_KEYWORD in u
def _open_sso_tab(page):
"""点击首页「登录」,等待新 tab 打开、跳转链结束且登录表单渲染完成后返回。
返回 (tab, already_logged):
already_logged=False → SSO 登录页(需填表)
already_logged=True → SSO 会话有效直接跳回大厅(登录成功,无需填表)"""
_dismiss_notice(page)
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT)
if not login_link:
login_link = page.ele('tag:a@@text():登录', timeout=TIMEOUT)
if not login_link:
config.log("未找到登录入口(可能残留上一账号登录态),清除 cookies 后重试", "WARN")
try:
page.clear_cache(cookies=True)
except Exception:
try:
page.run_js("document.cookie.split(';').forEach(c=>{"
"document.cookie=c.trim().split('=')[0]+"
"'=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'});")
except Exception:
pass
page.get(APPLY_URL)
time.sleep(2)
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT) \
or page.ele('tag:a@@text():登录', timeout=TIMEOUT)
if not login_link:
config.log("找不到登录入口(首页可能已是登录态)", "WARN")
return None, False
before_ids = set(page.tab_ids)
login_link.click()
tab = None
for _ in range(90): # 最多等 45 秒
time.sleep(0.5)
for tid in [i for i in page.tab_ids if i not in before_ids]:
try:
t = page.get_tab(tid)
except Exception:
continue
if _is_work_tab(t):
config.log(f"SSO 会话有效,已直接登录:{t.url}")
_close_extra_tabs(page, before_ids, t)
_dismiss_notice(t)
return t, True
if _sso_form_ready(t):
tab = t
break
if tab:
break
if tab is None:
if _sso_form_ready(page):
return page, False
config.log("点击登录后未检测到就绪的 SSO 登录页", "WARN")
return None, False
_close_extra_tabs(page, before_ids, tab)
return tab, False
def _close_extra_tabs(page, before_ids, keep_tab):
"""关掉一次「点登录」产生的多余新开 tab(中转页等),保持会话干净。"""
for tid in [i for i in page.tab_ids if i not in before_ids and i != keep_tab.tab_id]:
try:
page.get_tab(tid).close()
except Exception:
pass
def _try_login_once(tab, page, username, password, retry_index):
"""在 SSO tab 内完成一次填表 + 验证码 + 提交。返回 True 表示登录成功。"""
_wait_sso_ready(tab)
legal_tab = tab.ele('tag:div@@text()=法人用户', timeout=TIMEOUT)
if legal_tab:
legal_tab.click()
_human_pause(0.3, 0.8)
for _ in range(3):
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=2)
if active and active.text.strip() == '法人用户':
break
if legal_tab:
try:
legal_tab.click()
except Exception:
pass
time.sleep(1)
# 账号(统一社会信用代码)+ 密码
user_input = _find_input(tab, [
'css:input[placeholder*="统一社会信用代码"]',
'css:input[placeholder*="社会信用代码"]',
'css:#identifier',
])
if not user_input:
config.log("找不到账号输入框", "ERROR")
return False
user_input.clear()
user_input.input(username)
_human_pause()
pwd_input = _find_input(tab, ['css:#password', 'css:input[type="password"]'])
if not pwd_input:
config.log("找不到密码输入框", "ERROR")
return False
pwd_input.clear()
pwd_input.input(password)
_human_pause()
for attempt in range(RETRY_MAX):
config.log(f"--- 第 {retry_index}-{attempt + 1} 次验证码识别 ---")
img, code_input = _find_captcha(tab)
if not img or not code_input:
config.log("找不到验证码图片或输入框", "ERROR")
return False
img_bytes = _read_img_bytes(img)
if not img_bytes:
config.log("验证码图数据为空", "WARN")
time.sleep(1)
continue
try:
code = _recognize_captcha(img_bytes)
except Exception as e:
config.log(f"ddddocr 识别异常:{e}", "ERROR")
return False
config.log(f" 识别结果:{code!r}")
if not code:
_refresh_captcha(tab, img)
continue
code = code.upper() # 页面显示为大写,按大写提交
_dump_debug_captcha(img_bytes, code)
code_input.clear()
code_input.input(code)
_human_pause(0.3, 0.9)
btn = tab.ele('css:button[type="submit"]', timeout=TIMEOUT) \
or tab.ele('tag:button@@text():登录', timeout=TIMEOUT)
if not btn:
config.log("找不到登录提交按钮", "ERROR")
return False
_human_pause(0.2, 0.6)
btn.click()
ok, work_tab = _wait_login_result(tab, page)
if ok:
_try_login_once.work_tab = work_tab # 供 _do_login 保存会话
return True
_refresh_captcha(tab, img)
return False
def _wait_login_result(tab, page):
"""提交后轮询判定登录结果。返回 (ok, work_tab)。"""
before_ids = set(page.tab_ids)
for _ in range(30): # 最多等 15 秒
time.sleep(0.5)
for tid in [i for i in page.tab_ids if i not in before_ids]:
try:
t = page.get_tab(tid)
except Exception:
continue
if _is_work_tab(t):
config.log(f"登录成功(新开工作台 tab):{t.url}")
_close_extra_tabs(page, before_ids, t)
_dismiss_notice(t)
return True, t
try:
url = (tab.url or '').strip()
except Exception:
url = ''
if url.startswith('https://' + HOME_KEYWORD) and SSO_KEYWORD not in url and WORK_KEYWORD in url:
config.log(f"登录成功,已跳转:{url}")
_dismiss_notice(tab)
return True, tab
try:
err = tab.ele('css:.ant-message-error', timeout=0.5)
if err:
config.log(f"登录失败提示:{err.text}")
return False, None
except Exception:
pass
config.log("等待登录结果超时", "WARN")
return False, None
def _refresh_captcha(tab, img):
"""点击验证码图片刷新,校验 base64 src 是否真的变化(连续点 2 次)。"""
try:
old = img.attr('src') or ''
except Exception:
old = ''
for _ in range(2):
try:
img.click()
except Exception:
try:
img.click(by_js=True)
except Exception:
pass
for _p in range(10):
time.sleep(0.3)
try:
new = img.attr('src') or ''
except Exception:
new = old
if new and new != old:
return True
config.log("警告:验证码图片刷新后未变化", "WARN")
return False
LAST_SESSION = {'page': None, 'tab': None} # 登录成功后保留的浏览器会话(供后续网页操作使用)
def _teardown(page):
"""清 cookies/本地存储后关浏览器(账号切换彻底隔离,避免残留登录态)。"""
if page is None:
return
try:
page.clear_cache(cookies=True, local_storage=True, session_storage=True)
except Exception:
try:
page.clear_cache()
except Exception:
pass
try:
page.quit()
except Exception:
pass
def close_session():
"""清 cookies 并关闭当前保留的登录会话(每个账号业务办完后必须调用)。"""
_teardown(LAST_SESSION['page'])
LAST_SESSION['page'] = None
LAST_SESSION['tab'] = None
def _do_login(username, password):
"""打开浏览器现场完成登录(含图形验证码)。不做任何 cookies 缓存。
成功保留浏览器会话(工作台 tab 供后续导入操作),失败关闭浏览器。
返回 (ok, work_tab)。"""
from DrissionPage import ChromiumPage, ChromiumOptions
close_session() # 账号切换隔离
co = ChromiumOptions()
if HEADLESS:
co.headless()
co.auto_port(True) # 每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
co.set_argument('--start-maximized')
co.set_pref('credentials_enable_service', False)
co.set_pref('profile.password_manager_enabled', False)
page = ChromiumPage(co)
work_tab_holder = {'tab': None}
def _finish(ok):
if ok:
LAST_SESSION['page'] = page
LAST_SESSION['tab'] = work_tab_holder['tab']
return True, work_tab_holder['tab']
_teardown(page)
return False, None
try:
page.get(APPLY_URL)
_human_pause(1.0, 2.5)
tab = None
for retry in range(FLOW_RETRY):
try:
_dismiss_notice(page)
if tab is not None:
try:
if SSO_KEYWORD not in tab.url:
tab = None
except Exception:
tab = None
if tab is None:
tab, already = _open_sso_tab(page)
if tab is None:
config.log(f"进入 SSO 登录页失败(第 {retry + 1}/{FLOW_RETRY} 轮)", "WARN")
time.sleep(2)
continue
if already:
work_tab_holder['tab'] = tab
return _finish(True)
if _try_login_once(tab, page, username, password, retry + 1):
work_tab_holder['tab'] = getattr(_try_login_once, 'work_tab', None) or tab
return _finish(True)
try:
tab.refresh()
time.sleep(2)
except Exception:
pass
except Exception as e:
config.log(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}", "WARN")
time.sleep(1)
config.log("登录失败(验证码识别未通过或流程异常)", "ERROR")
return _finish(False)
except Exception:
_teardown(page)
raise
def ensure_login(username, password):
"""以指定账号现场登录政务平台(无缓存,每次真登录)。
返回 JSON 安全 dict:{success, username, message}"""
username = (username or '').strip()
password = (password or '').strip()
if not (username and password):
return {"success": False, "username": username,
"message": "登录账号/密码缺失(台账未取到账号密码)"}
ok, _work_tab = _do_login(username, password)
if ok:
return {"success": True, "username": username, "message": "登录成功"}
return {"success": False, "username": username,
"message": "登录失败(验证码识别未通过或流程异常)"}