Files
37duAutomation/plugins/sb_person_change/login.py
T
puddy 0ab43d0ed8 refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移:
1.  将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构
2.  移动并整理了插件目录结构,将插件统一放入根级plugins/
3.  调整了前端项目的路径与配置,统一前后端开发构建流程
4.  清理了废弃的旧版app/目录与冗余的构建中间文件
5.  更新了.gitignore与README.md,适配新的项目结构
2026-09-14 17:46:09 +08:00

514 lines
20 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 -*-
"""重庆人社网上服务大厅(政务平台)法人登录模块(sb_person_change 插件)。
自 workflows/XQ0014 sb_login.py 迁移:
- 每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务;
- 不做 cookies 缓存(政务平台 cookies 极易失效),统一每次现场真登录;
- SSO 完整流程 + ddddocr 识别图形验证码(验证码 5 次/轮 × 流程 3 轮)。
改造点:print → config.log;验证码调试落盘受 config.DEBUG_MODE 控制;
去掉影刀 glv/main 入口。默认账号兜底读共享 .env(%LOCALAPPDATA%\37duAutomation\.env)。
"""
import base64
import os
import random
import time
from DrissionPage import ChromiumPage, ChromiumOptions
from dotenv import load_dotenv
from . import config
# 默认账号只从共享 .env 读取,不内置明文;主流程按参保单位从台账取号传入,这里仅作兜底。
if os.path.exists(os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation', '.env')):
load_dotenv(os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation', '.env'))
load_dotenv()
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 _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):
"""可选:落盘验证码调试图片(仅 config.DEBUG_MODE 开启时),便于分析识别失败样本。"""
if not config.DEBUG_MODE:
return
try:
cfg_dir = config.DEBUG_DIR / "captcha"
cfg_dir.mkdir(parents=True, exist_ok=True)
path = cfg_dir / 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}")
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:
# 兜底:激活面板内第一个 base64 图
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(如 #user-sso-pc)。"""
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 _is_work_tab(t):
"""是否登录完成的工作台页(onlineoffice/index)。
必须 origin 前缀匹配 + 路径含 onlineoffice/index——跳转链中间页(zwykb 授权页、
ggfw 回调页)的 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)
# 登录入口:loginBox 内的第一个 <a>(「登录」,无 href)
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:
# 可能残留上一账号登录态(首页已免登录):清除 cookies 后刷新重试一次
config.log("未找到登录入口(可能残留上一账号登录态),清除 cookies 后重试")
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("找不到登录入口(首页可能已是登录态)")
return None, False
before_ids = set(page.tab_ids)
login_link.click()
# 点击「登录」后是中转跳转链:轮询所有新开 tab,直到某个 tab 的 URL 稳定停在
# SSO 且「法人用户」登录表单真实渲染出来(避免拿到闪现中的中转页就操作);
# 若 SSO 会话仍有效(同账号二次登录),新 tab 会直接跳回大厅页 → 视为已登录
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:
# 部分场景可能不新开 tab 而是当前页跳转
if _sso_form_ready(page):
return page, False
config.log("点击登录后未检测到就绪的 SSO 登录页")
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 _wait_sso_ready(tab):
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作,
避免跳转/React 重渲染过程中拿到元素随即失效(元素对象已失效)。"""
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 _try_login_once(tab, page, username, password, retry_index):
"""在 SSO tab 内完成一次填表 + 验证码 + 提交。返回 True 表示登录成功。
所有动作间加随机延时,模拟人工节奏,降低脚本特征。"""
_wait_sso_ready(tab)
# 法人用户 tab:精确文本匹配(text(): 模糊会命中包含文字的外层容器,如 #user-sso-pc)
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)
# 账号(统一社会信用代码)+ 密码
# SSO 法人用户表单真实结构(2026-09 探针实测):
# 账号框 id=identifier placeholder「请输入统一社会信用代码」
user_input = _find_input(tab, [
'css:input[placeholder*="统一社会信用代码"]',
'css:input[placeholder*="社会信用代码"]',
'css:#identifier',
])
if not user_input:
config.log("找不到账号输入框")
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("找不到密码输入框")
return False
pwd_input.clear()
pwd_input.input(password)
_human_pause()
# 图形验证码:base64 内嵌图(从验证码输入框容器定位,避免抓到页面其它图标)
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("找不到验证码图片或输入框")
return False
img_bytes = _read_img_bytes(img)
if not img_bytes:
config.log("验证码图数据为空")
time.sleep(1)
continue
try:
code = _recognize_captcha(img_bytes)
except Exception as e:
config.log(f"ddddocr 识别异常:{e}")
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)
# 提交:登录按钮(button[type=submit],文案「登 录」)
btn = tab.ele('css:button[type="submit"]', timeout=TIMEOUT) \
or tab.ele('tag:button@@text():登录', timeout=TIMEOUT)
if not btn:
config.log("找不到登录提交按钮")
return False
_human_pause(0.2, 0.6) # 点提交前再停顿一下
btn.click()
# 等待结果:SSO tab 跳回大厅 / 新开 onlineoffice 工作台 tab = 成功;错误提示 = 刷新重试
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)
# 成功标志 1:登录后新开的 onlineoffice 工作台 tab
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
# 成功标志 2:SSO tab 自身跳到工作台页(origin 前缀匹配,防 redirectUrl 参数误判)
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
# ant-message 错误提示(验证码错误/账号密码错误等)
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("等待登录结果超时")
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
# 刷新是异步的:轮询 src 变化(最多 3 秒)
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
# src 还没变,再点一次
config.log("警告:验证码图片刷新后未变化")
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)。"""
# 账号切换隔离:先关掉上一账号的浏览器会话(auto_port 临时目录本就不互通,双保险)
close_session()
co = ChromiumOptions()
if HEADLESS:
co.headless()
# auto_port:每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
co.auto_port(True)
co.set_argument('--start-maximized') # 浏览器启动即全屏(最大化),避免小窗口下元素被折叠/遮挡
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)
# 登录 tab 跨轮次复用:只在丢失/失效时才重新点「登录」,
# 避免每轮重开浏览器 tab 越积越多(手动只点一次,代码不能反复点)
if tab is not None:
try:
if SSO_KEYWORD not in tab.url:
tab = None # 已跳走(登录成功或会话变化),需重新进入
except Exception:
tab = None # tab 已关闭/失效
if tab is None:
tab, already = _open_sso_tab(page)
if tab is None:
config.log(f"进入 SSO 登录页失败(第 {retry + 1}/{FLOW_RETRY} 轮)")
time.sleep(2)
continue
if already:
# 同账号 SSO 会话仍有效:免验证码直接登录成功
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)
# 登录失败:复用同一 tab 刷新重来,不再重复点「登录」
try:
tab.refresh()
time.sleep(2)
except Exception:
pass
except Exception as e:
# 元素失效/页面刷新等异常:不中断整体流程,进入下一轮
config.log(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}")
time.sleep(1)
config.log("登录失败(验证码识别未通过或流程异常)")
return _finish(False)
except Exception:
# 整体异常也要保证清理(失败场景不留会话)
_teardown(page)
raise
def ensure_login(username=None, password=None):
"""以指定账号现场登录政务平台(无缓存,每次真登录)。
返回 dict:{success, username, message}"""
# 未传账号时回落到 .env 默认账号(兜底场景)
username = (username or os.getenv('sb_login_username', '') or '').strip()
password = (password or os.getenv('sb_login_password', '') or '').strip()
if not (username and password):
return {"success": False, "username": username,
"message": "登录账号/密码缺失(台账未取到且 .env 未配置 sb_login_username / sb_login_password)"}
ok, _work_tab = _do_login(username, password)
if ok:
return {"success": True, "username": username, "message": "登录成功"}
return {"success": False, "username": username,
"message": "登录失败(验证码识别未通过或流程异常)"}