chore: 清理废弃插件与冗余文档,重构项目目录结构

1.  删除旧版xq0031_xq0032插件的冗余UI源码与配置文件
2.  迁移并标准化XQ0001-0100系列需求的插件、文档与工作流目录
3.  清理过期的需求列表、评分文档与流程底稿
4.  更新.gitignore匹配规则,适配新的目录结构
This commit is contained in:
2026-09-21 16:59:05 +08:00
parent b1ae4e5111
commit d1af551eac
192 changed files with 5335 additions and 2694 deletions
@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*-
"""验证码采集探针:只截图 + 尝试刷新,绝不提交登录。用完可删。"""
import sys
import time
import hashlib
import os
sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0014 社保系统增减员办理")
import sb_login
from DrissionPage import ChromiumPage, ChromiumOptions
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'debug_captcha')
os.makedirs(OUT, exist_ok=True)
co = ChromiumOptions()
co.auto_port(True)
page = ChromiumPage(co)
try:
page.get(sb_login.APPLY_URL)
time.sleep(2)
sb_login._dismiss_notice(page)
tab = sb_login._open_sso_tab(page)
if tab is None:
print("PROBE: 未进入 SSO 登录页")
sys.exit(1)
sb_login._wait_sso_ready(tab)
legal = tab.ele('tag:div@@text()=法人用户', timeout=10)
if legal:
legal.click()
time.sleep(1)
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=3)
print("PROBE: 当前激活tab =", active.text.strip() if active else None)
for i in range(5):
img, code_input = sb_login._find_captcha(tab)
if not img:
print("PROBE: 找不到验证码图")
break
data = sb_login._read_img_bytes(img)
h = hashlib.md5(data).hexdigest()[:10]
path = os.path.join(OUT, f"probe_{i}_{h}.png")
with open(path, 'wb') as f:
f.write(data)
print(f"PROBE: 第{i+1}张 md5={h} size={len(data)} -> {os.path.basename(path)}")
if i < 4:
ok = sb_login._refresh_captcha(tab, img)
print(f"PROBE: 刷新{'成功' if ok else '失败'}")
finally:
try:
page.quit()
except Exception:
pass
print("PROBE: 采集完成(未提交登录)")
@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*-
"""探针:打开 SSO 登录页(法人用户 tab),dump 所有输入框的真实属性,
用于修正 sb_login.py 的选择器。用完可删。"""
import sys
import time
sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0014 社保系统增减员办理")
import sb_login
from DrissionPage import ChromiumPage, ChromiumOptions
co = ChromiumOptions()
co.auto_port(True)
page = ChromiumPage(co)
try:
page.get(sb_login.APPLY_URL)
time.sleep(2)
sb_login._dismiss_notice(page)
tab = sb_login._open_sso_tab(page)
if tab is None:
print("PROBE: 未进入 SSO 登录页")
sys.exit(1)
print("PROBE: SSO URL =", tab.url)
sb_login._wait_sso_ready(tab)
# 点法人用户 tab(精确文本匹配,避免命中包含该文字的外层容器 div)
legal = tab.ele('tag:div@@text()=法人用户', timeout=10)
print("PROBE: 法人用户tab元素 =", legal, "| tag:", legal.tag if legal else None,
"| class:", (legal.attr('class') if legal else None))
if legal:
legal.click()
time.sleep(1.5)
active_btn = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=3)
print("PROBE: 当前激活tab =", active_btn.text.strip() if active_btn else None)
# dump 当前激活面板内的所有输入框
panel = tab.ele('css:.ant-tabs-tabpane-active', timeout=5)
inputs = panel.eles('tag:input') if panel else tab.eles('tag:input')
print(f"PROBE: 共 {len(inputs)} 个 input")
for i, ip in enumerate(inputs):
try:
print(f"[{i}] type={ip.attr('type')} placeholder={ip.attr('placeholder')!r} "
f"id={ip.attr('id')!r} name={ip.attr('name')!r} class={(ip.attr('class') or '')[:60]!r}")
except Exception as e:
print(f"[{i}] 读取失败: {e}")
# 顺带 dump 按钮
for i, b in enumerate(panel.eles('tag:button') if panel else tab.eles('tag:button')):
try:
print(f"BTN[{i}] type={b.attr('type')} class={(b.attr('class') or '')[:50]!r} text={b.text.strip()!r}")
except Exception as e:
print(f"BTN[{i}] 读取失败: {e}")
finally:
try:
page.quit()
except Exception:
pass
@@ -0,0 +1,622 @@
# -*- coding: utf-8 -*-
"""
@FileName: check_review.py
@Description: XQ0014 重庆社保系统增减员办理(核查-回盘)—— 单文件自包含版
增员申报(import_add.py)提交后,平台审核存在滞后。本脚本对源名单中
「办理状态=待审核」的人员所在参保单位,逐个登录重庆人社政务平台核查审核结论:
流程(每个参保单位):
1. 登录(复用同目录 sb_login,法人用户 + 图形验证码)
2. 单位办事 → 城保参保单位人员增加 → 在线办理(与增员同一入口)
3. 左侧菜单点「已申报查询」→ 读表格第一条「当前状态」
非「已办结」→ 跳过该单位(审核还没走完)
4. 「已办结」→ 点「查看」,监听 queryYsbWs04orWs01 接口拿查询参数
(asl001/aaa121/aab001),再用页内 XHR 重放接口翻页取全量(防分页漏数据)
5. 按 aac002 证件号码匹配本单位「待审核」人员,回写源名单:
- 审核通过 → 办理状态 = 参保成功
- 不通过 + 400系统错误 → 先记录不动状态,全部单位核查完后统一清空办理状态
(回到待办,之后重新执行8号需求制作名单完成新增)
- 不通过 + 其它原因 → 办理状态 = 参保失败,审核意见追加写备注(不覆盖)
6. 回盘打印:每个账号核查完都下载回盘表到 DISK_DIR
(人员增减申请回盘表_单位_下载日期.xlsx),核对养老/失业/医疗/工伤/生育
五项参保状态:全「参保缴费」→ 备注追加个人编号;否则备注追加个人编号 +
异常字段名及内容(都是追加,不覆盖)
7. 台账回写:与 import_add 同一套 JSON 缓存 + 运行结束统一回写 Excel 机制
依赖(与 import_add 相同):pandas openpyxl DrissionPage python-dotenv ddddocr
运行:python check_review.py
"""
import os
import re
import sys
import json
import time
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse, parse_qsl, urlencode
# ---- 单文件运行支持:本目录加入 sys.path,复用同目录 import_add / sb_login ----
_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
try:
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
f"缺失依赖详情: {_import_err}")
import import_add # 同目录:复用名单/台账读取、登录后页面导航、回写缓存机制
import sb_login
# ==================== 1. 配置 ====================
CHECK_STATUS = "待审核" # 核查范围:办理状态为该值的人员
DONE_STATUS = "已办结" # 已申报查询里第一条的该状态才继续查看
PASS_STATUS = "参保成功" # 审核通过 → 办理状态
FAIL_STATUS = "参保失败" # 审核不通过(非系统错误)→ 办理状态
ERR_400_KEYWORD = "status 400" # aae111 含该关键字 = 系统错误,需重新增员
MENU_QUERY = "已申报查询" # 业务页左侧菜单
API_KEYWORD = "queryYsbWs04orWs01" # 已申报明细查询接口(监听 + 重放)
API_UNIT_INFO = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/declare/server/gourd/"
"cloud/ggfw/declare/query/DwCx/dwyl/getAab001") # 单位信息接口(页面加载完成标志)
MENU_PAGE_URL = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/"
"onlineoffice/OdCommon") # 左侧菜单页(刷新/直跳即可回到菜单)
PAGE_SIZE = 10 # 重放接口每页条数(与平台默认一致,翻页取全量)
MAX_PAGES = 50 # 重放翻页上限(防死循环)
CHECK_LIMIT = None # 每次运行最多核查的单位数(None=不限制)
RUN_400_CLEAR = True # 400系统错误:True=运行结束后统一清空办理状态回待办(重新走8号+增员)
# ---- 回盘打印下载与核对 ----
DISK_DIR = r"D:\资料\人资\社保系统增减员办理\回盘打印\新参保-增员" # 回盘文件保存目录
REPLAY_PREFIX = "人员增减申请回盘表" # 保存文件名:前缀_单位_日期.xlsx
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
"工伤参保状态", "生育参保状态"] # 需核对的三险五项状态列
INS_OK = "参保缴费" # 正常状态值
# ==================== 2. 核查任务读取 ====================
def load_check_tasks(exclude_ids=frozenset()):
"""读取源名单,筛选 办理状态=待审核 的行,按参保单位分组。
返回 [{unit, count, cids(set)}];同时把源文件信息写回 import_add 全局
(flush_writeback 依赖 SOURCE_FILE_USED / SOURCE_SHEET_USED)。
exclude_ids:上次运行已回写的人员身份证号(防重复核查)。
"""
source_file = import_add._latest_file(import_add.SOURCE_DIR, import_add.SOURCE_GLOB)
now = datetime.now()
xl = pd.ExcelFile(source_file)
sheet_name = import_add._pick_sheet(xl, f"{now:%Y%m}参保名单", "参保名单")
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
import_add.SOURCE_FILE_USED, import_add.SOURCE_SHEET_USED = source_file, sheet_name
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
status = df[import_add.STATUS_COL].astype(str).str.strip()
mask = (
(df[import_add.REGION_COL].astype(str).str.strip() == import_add.REGION)
& (df[import_add.TYPE_COL].astype(str).str.strip() == import_add.OPERATION_TYPE)
& (status == CHECK_STATUS)
)
sub = df[mask].copy()
if exclude_ids and '身份证号码' in sub.columns:
before = len(sub)
ref = [import_add._norm_id(x) for x in exclude_ids]
sub = sub[~sub['身份证号码'].map(lambda v: import_add._id_hit(import_add._norm_id(v), ref))]
dropped = before - len(sub)
if dropped:
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复核查)")
if sub.empty:
print(f"没有筛选到数据({import_add.REGION} ∩ {import_add.OPERATION_TYPE} ∩ 办理状态={CHECK_STATUS})")
return []
tasks = []
for unit, g in sub.groupby(sub[import_add.UNIT_COL].astype(str).str.strip()):
cids = {import_add._norm_id(v) for v in g['身份证号码']}
cids.discard('')
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
tasks.sort(key=lambda t: t['unit'])
print(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / {len(tasks)} 个参保单位(办理状态={CHECK_STATUS})")
return tasks
# ==================== 3. 网页操作 ====================
def _open_query_menu(tab):
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
import_add._click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
f'左侧菜单「{MENU_QUERY}」')
import_add._dismiss_popups(tab)
deadline = time.time() + 15
while time.time() < deadline:
for tb in tab.eles('tag:table'):
try:
ths = [th.text.strip() for th in tb.eles('tag:th')]
except Exception:
continue
if '当前状态' in ths and '操作' in ths:
return tb
time.sleep(0.5)
raise RuntimeError(f"点击「{MENU_QUERY}」后未出现申报记录表")
def _read_first_row(table):
"""读申报记录表第一条:返回 (当前状态, 查看按钮元素)。无记录返回 (None, None)。"""
row = table.ele('css:tbody tr.ant-table-row', timeout=3) \
or table.ele('css:tbody tr', timeout=1)
if row is None:
return None, None
ths = [th.text.strip() for th in table.eles('tag:th')]
i_status = ths.index('当前状态')
tds = [td.text.strip() for td in row.eles('tag:td')]
status = tds[i_status] if len(tds) > i_status else ''
view = None
for sel in ('tag:a@@text()=查看', 'tag:span@@text()=查看', 'text=查看'):
try:
view = row.ele(sel, timeout=1)
except Exception:
view = None
if view:
break
return status, view
def _capture_query_url(page, tab, view):
"""点「查看」并监听明细查询接口,返回请求 URL。
明细可能在当前 tab 打开也可能新开 tab:两个方向都轮询监听。"""
before = set(page.tab_ids)
tab.listen.start(API_KEYWORD)
new_tabs = []
packet = None
try:
try:
view.click()
except Exception:
view.click(by_js=True)
deadline = time.time() + 25
while time.time() < deadline and packet is None:
# 新开 tab 也挂上监听(明细页可能新 tab 加载接口)
for tid in [i for i in page.tab_ids if i not in before and i not in new_tabs]:
new_tabs.append(tid)
try:
page.get_tab(tid).listen.start(API_KEYWORD)
except Exception:
pass
try:
packet = tab.listen.wait(count=1, timeout=2)
except Exception:
packet = None
if packet is None:
for tid in new_tabs:
try:
packet = page.get_tab(tid).listen.wait(count=1, timeout=0.5)
except Exception:
packet = None
if packet:
break
finally:
for t in [tab] + [page.get_tab(tid) for tid in new_tabs if tid in page.tab_ids]:
try:
t.listen.stop()
except Exception:
pass
if not packet:
raise RuntimeError("点击查看后未监听到明细查询接口(queryYsbWs04orWs01)")
url = packet.request.url
print(f" 已捕获明细接口:{url[:100]}...")
return url
def _fetch_via_xhr(tab, url):
"""页内同步 XHR GET(自带登录态 cookies),返回响应文本。"""
js = ("const xhr=new XMLHttpRequest();"
"xhr.open('GET',arguments[0],false);"
"xhr.setRequestHeader('Accept','application/json, text/javascript');"
"xhr.send();return xhr.responseText;")
return tab.run_js(js, url)
def _wait_unit_loaded(tab, unit_name, timeout=40):
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
该接口没返回时页面没加载出单位,后续已申报查询/回盘打印都拿不到数据。
接口轮询失败但页面已出现单位名时也视为加载成功(可能错过响应窗口)。
返回 data[0](含 aab001、aab004 平台单位全称),页面已加载但接口拿不到时返回 {},超时返回 None。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
raw = _fetch_via_xhr(tab, API_UNIT_INFO)
data = (json.loads(raw).get('data') or [None])[0]
if data and data.get('aab001'):
print(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
return data
except Exception:
pass
# 接口没拿到但页面已经出现单位名 → 页面其实加载完了,不必再等
try:
if tab.ele(f'text:{unit_name}', timeout=0.5):
print(f" 页面已显示单位「{unit_name}」,视为加载完成(接口轮询未取到全称)")
return {}
except Exception:
pass
time.sleep(1)
return None
def _replay_query_all(tab, captured_url):
"""用捕获的请求参数重放接口翻页,取全量明细行。
返回 [{name, cid, conclusion, opinion}, ...](字段取 aac003/aac002/aae110s/aae111)。"""
parsed = urlparse(captured_url)
base_params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
if k != 'pageIndex']
root = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
rows, total = [], None
for idx in range(MAX_PAGES):
params = base_params + [('pageIndex', json.dumps(
{"pageIndex": idx, "pageSize": PAGE_SIZE}, separators=(',', ':')))]
full = f"{root}?{urlencode(params)}"
raw = _fetch_via_xhr(tab, full)
if not raw:
raise RuntimeError(f"接口重放第 {idx + 1} 页返回空")
payload = json.loads(raw)
data = payload.get('data') or {}
items = data.get('data') or []
if total is None:
total = data.get('total')
rows.extend(items)
print(f" 接口重放第 {idx + 1} 页:取到 {len(items)} 条(累计 {len(rows)}/{total})")
if not items or (total is not None and len(rows) >= total):
break
results = []
for it in rows:
results.append({
"name": str(it.get('aac003') or '').strip(),
"cid": import_add._norm_id(it.get('aac002')),
"conclusion": str(it.get('aae110s') or '').strip(),
"opinion": str(it.get('aae111') or '').strip(),
})
# 平台登记的参保单位全称(aab004),用于回盘文件命名
unit_full = ""
for it in rows:
v = str(it.get('aab004') or '').strip()
if v:
unit_full = v
break
return results, unit_full
# ==================== 4. 结论回写 ====================
def build_writeback(results, task_cids, unit_name):
"""按回写规则处理明细,返回 (status_map, remark_map, redo400_list, log_lines)。
只处理本单位「待审核」人员(证件号码精确匹配),其余仅记录日志。
400系统错误不立即清状态:先记录,运行结束后统一清空办理状态回待办再新增。"""
status_map, remark_map, redo400, logs = {}, {}, [], []
for r in results:
if not r['cid'] or r['cid'] not in task_cids:
continue
concl, opinion = r['conclusion'], r['opinion']
line = f" {r['name']}({r['cid']}):{concl}"
if concl == '审核通过':
status_map[r['cid']] = PASS_STATUS
line += f" → 办理状态={PASS_STATUS}"
elif concl == '不通过':
if ERR_400_KEYWORD in opinion:
# 系统错误:仅记录,运行结束后统一清空办理状态回待办重新增员
if RUN_400_CLEAR:
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
line += " → 400系统错误,已记录(结束后统一清状态回待办重新增员)"
else:
status_map[r['cid']] = FAIL_STATUS
remark_map[r['cid']] = opinion or '审核不通过'
line += f" → 办理状态={FAIL_STATUS},备注追加:{opinion[:60]}"
else:
line += " → 非终态结论,跳过"
logs.append(line)
return status_map, remark_map, redo400, logs
# ==================== 4b. 回盘打印下载与核对 ====================
def _clean_cell(v):
"""单元格值转干净字符串:浮点整数去掉 .0,其余去首尾空白。"""
if v is None:
return ""
if isinstance(v, float) and v.is_integer():
return str(int(v))
return str(v).strip()
def _download_huipan(page, biz_tab, unit):
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
返回保存的文件 Path。"""
save_dir = Path(DISK_DIR)
save_dir.mkdir(parents=True, exist_ok=True)
target = save_dir / f"{REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
try:
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」')
except Exception:
# 点「查看」后会跳到明细详情页,左侧菜单不可见:直跳 OdCommon 菜单页即可
try:
print(" 当前页看不到左侧菜单,直跳菜单页...")
biz_tab.get(MENU_PAGE_URL)
time.sleep(2)
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(菜单页)')
except Exception:
# 直跳也不行:重开业务页再点(最后兜底)
biz_tab = import_add._open_business_page(page, sb_login.LAST_SESSION['tab'])
import_add._dismiss_popups(biz_tab)
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(重开业务页)')
import_add._dismiss_popups(biz_tab)
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接/文本)
btn = None
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印',
'tag:span@@text()=回盘打印'):
try:
btn = biz_tab.ele(sel, timeout=2)
except Exception:
btn = None
if btn:
break
if btn is None:
raise RuntimeError("未找到页内「回盘打印」按钮")
biz_tab.set.download_path(str(save_dir))
before = {f.name for f in save_dir.iterdir() if f.is_file()}
try:
btn.click()
except Exception:
btn.click(by_js=True)
# 轮询等下载:新文件出现且大小连续2秒稳定(最多90秒)
new_file, last_size, stable = None, -1, 0
deadline = time.time() + 90
while time.time() < deadline:
time.sleep(1)
files = [f for f in save_dir.iterdir() if f.is_file() and f.name not in before
and f.suffix.lower() not in ('.crdownload', '.tmp')]
if not files:
stable, last_size = 0, -1
continue
f = max(files, key=lambda x: x.stat().st_mtime)
size = f.stat().st_size
if size > 0 and size == last_size:
stable += 1
if stable >= 2:
new_file = f
break
else:
stable = 0
last_size = size
if new_file is None:
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件")
os.replace(new_file, target) # 同名覆盖,保证文件名=回盘表_单位_日期.xlsx
return target
def _verify_huipan(filepath, task_cids):
"""读回盘表(表头在第2行),按身份证号核对五项参保状态,生成备注回写内容。
同人多条记录:取参保缴费数量最多的那条(并列取先出现的)。
返回 (remark_map, logs)。"""
df = pd.read_excel(filepath, header=1)
df.columns = [str(c).strip() for c in df.columns]
need = ['个人编号', '身份证号'] + INS_STATUSES
missing = [c for c in need if c not in df.columns]
if missing:
raise RuntimeError(f"回盘表缺少列:{missing}")
remarks, logs = {}, []
for cid in task_cids:
rows = df[df['身份证号'].map(
lambda v: import_add._id_hit(import_add._norm_id(_clean_cell(v)), [cid]))]
if rows.empty:
remarks[cid] = "未查询到回盘记录"
logs.append(f" 证件{cid}:回盘表中未找到记录 → 备注追加「未查询到回盘记录」")
continue
# 同人多条记录:取参保缴费数量最多的那条(并列取先出现的)
best_row, best_ok = None, -1
for _, row in rows.iterrows():
ok = sum(1 for c in INS_STATUSES if _clean_cell(row[c]) == INS_OK)
if ok > best_ok:
best_row, best_ok = row, ok
target = best_row
bh = _clean_cell(target['个人编号'])
if best_ok == len(INS_STATUSES):
# 五项全参保缴费 = 正常,备注只追加个人编号
remarks[cid] = f"个人编号:{bh}"
logs.append(f" 证件{cid}:五项均参保缴费,个人编号 {bh} → 备注追加")
else:
# 有不是参保缴费的:记录个人编号 + 异常字段名和对应内容
bad = [f"{c}:{_clean_cell(target[c])}"
for c in INS_STATUSES if _clean_cell(target[c]) != INS_OK]
remarks[cid] = f"个人编号:{bh};" + "、".join(bad)
logs.append(f" 证件{cid}:参保状态异常 → {';'.join(bad)}(个人编号 {bh})→ 备注追加")
return remarks, logs
def _do_huipan(page, biz_tab, task, res, unit_full="", fail_cids=()):
"""每个账号核查完都执行:下载回盘记录 + 核对参保状态 + 备注追加(含与核查备注合并)。
文件名单位优先用平台 aab004 全称,未取到(未办结跳过等)退回源名单参保单位名。
fail_cids:审核不通过(参保失败)人员,平台无其回盘记录,跳过「未查询到回盘记录」回写。"""
name_for_file = (unit_full or task['unit']).strip()
if unit_full and unit_full != task['unit']:
print(f" 使用平台单位全称命名:{unit_full}")
print(" 开始回盘打印下载...")
hp_file = _download_huipan(page, biz_tab, name_for_file)
print(f" 回盘文件已保存:{hp_file}")
hp_remarks, hp_logs = _verify_huipan(hp_file, task['cids'])
for line in hp_logs:
print(line)
for cid in fail_cids:
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
hp_remarks.pop(cid)
print(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
# 与核查阶段已生成的备注合并(writeback_source 按证件号覆盖,需手动拼接)
for cid in list(hp_remarks):
old = import_add._PENDING_REMARK.get(cid)
if old:
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
if hp_remarks:
import_add.writeback_source({}, hp_remarks)
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"
# ==================== 5. 单个单位完整核查 ====================
def do_unit_check(task):
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
page = sb_login.LAST_SESSION.get('page')
work_tab = sb_login.LAST_SESSION.get('tab')
if page is None or work_tab is None:
return {"success": False, "message": "无有效登录会话"}
res = {"success": False, "checked": 0, "passed": 0, "failed": 0,
"redo400": [], "skipped": False}
try:
import_add._shot(work_tab, "c1_workbench")
biz_tab = import_add._open_business_page(page, work_tab)
import_add._dismiss_popups(biz_tab)
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
if unit_info is None:
# 页面没加载出单位:重开一次业务页再等
print(" 单位信息未加载,重开业务页重试...")
biz_tab = import_add._open_business_page(page, work_tab)
import_add._dismiss_popups(biz_tab)
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
if unit_info is None:
res.update(success=True, skipped=True,
message="单位信息未加载(getAab001无数据),跳过")
return res
unit_full = str(unit_info.get('aab004') or '').strip() # 平台单位全称,用于回盘命名
fail_cids = set() # 审核不通过(参保失败)人员:平台无回盘记录,回盘阶段跳过其未查询备注
_shot_c(biz_tab, "c2_biz_page")
table = _open_query_menu(biz_tab)
_shot_c(biz_tab, "c3_query_list")
status, view = _read_first_row(table)
if not status:
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
elif status != DONE_STATUS:
res.update(success=True, skipped=True,
message=f"第一条状态「{status}」非{DONE_STATUS},跳过")
else:
print(f" 第一条状态:{status},点击查看读取审核结论")
url = _capture_query_url(page, biz_tab, view)
results, detail_full = _replay_query_all(biz_tab, url)
unit_full = unit_full or detail_full
_shot_c(biz_tab, "c4_detail_fetched")
if not results:
res.update(success=True, message="明细接口返回 0 条,跳过")
else:
status_map, remark_map, redo400, logs = build_writeback(
results, task['cids'], task['unit'])
fail_cids = {cid for cid, st in status_map.items() if st == FAIL_STATUS}
for line in logs:
print(line)
if status_map or remark_map:
import_add.writeback_source(status_map, remark_map)
n_match = len([r for r in results if r['cid'] in task['cids']])
n_pass = len([v for v in status_map.values() if v == PASS_STATUS])
n_fail = len([v for v in status_map.values() if v == FAIL_STATUS])
res.update(
success=True,
checked=n_match,
passed=n_pass,
failed=n_fail,
redo400=redo400,
message=(f"核查{n_match}条,通过{n_pass} 失败{n_fail} "
f"400系统错误{len(redo400)}(结束后统一清状态)"))
# 回盘打印:每个账号核查完都要下载回盘记录并核对参保状态(无论是否已办结)
try:
_do_huipan(page, biz_tab, task, res, unit_full, fail_cids)
except Exception as e:
res["huipan"] = f"回盘打印失败:{e}"
print(f" 回盘打印失败:{e}")
return res
except Exception as e:
res["message"] = f"核查异常:{e}"
return res
def _shot_c(tab, name):
"""核查流程调试截图(沿用 import_add 的 DEBUG_MODE 开关,前缀 c 区分)。"""
import_add._shot(tab, name)
# ==================== 6. 逐单位登录 + 核查 ====================
def process_units(tasks, accounts):
"""逐参保单位:登录 → 已申报查询核查 → 回写。每账号办完清 cookies 关浏览器。"""
results = []
for i, task in enumerate(tasks, 1):
print(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人待审核)==========")
acc = accounts.get(task['unit'])
try:
login_res = sb_login.main({"username": acc["username"], "password": acc["password"]})
except Exception as e:
login_res = {"success": False, "message": f"登录调用异常:{e}"}
print(f"登录结果:{login_res.get('message')}")
try:
if login_res.get("success"):
web_res = do_unit_check(task)
print(f"核查结果:{web_res.get('message')}")
results.append({**task, **web_res})
else:
results.append({**task, "success": False, "message": login_res.get("message", "")})
finally:
sb_login.close_session()
return results
# ==================== 7. 主流程 ====================
def run():
"""主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
recovered_ids = import_add._load_ckpt()
tasks = load_check_tasks(exclude_ids=recovered_ids)
if recovered_ids:
print("\n检测到上次未回写的内容,先统一回写:")
try:
import_add.flush_writeback()
except Exception as e:
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
if not tasks:
return {"success": True, "message": "无待核查数据", "total": 0, "done": 0}
accounts = import_add.load_accounts([t['unit'] for t in tasks])
# 预检:账号齐备才继续(与增员一致的严格预检)
errors = []
for t in tasks:
acc = accounts.get(t['unit'])
if acc is None:
errors.append(f"[{t['unit']}] 台账未匹配")
elif not acc['username'] or not acc['password']:
errors.append(f"[{t['unit']}] 账号或密码缺失")
if errors:
print("\n预检未通过:")
for e in errors:
print(f" - {e}")
return {"success": False, "message": "预检未通过,详见日志", "total": len(tasks), "done": 0}
todo = tasks[:CHECK_LIMIT]
results = process_units(todo, accounts)
# 400系统错误:核查时只记录,全部单位核查完后统一清空办理状态回待办(重新走8号+增员)
redo_all = [p for r in results for p in (r.get("redo400") or [])]
if redo_all:
import_add.writeback_source({p['cid']: "" for p in redo_all}, {})
print(f"\n400系统错误共 {len(redo_all)} 人,已统一清空办理状态回待办,"
f"请重新执行8号需求制作名单后增员:")
for p in redo_all:
print(f" - {p['name']}({p['cid']}){p['unit']}")
try:
import_add.flush_writeback()
except Exception as e:
print(f"回写失败:{e}")
ok = [r for r in results if r["success"]]
fail = [r for r in results if not r["success"]]
skip = [r for r in ok if r.get("skipped")]
print(f"\n========== 汇总 ==========")
print(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,失败 {len(fail)} 家")
for r in fail:
print(f" ✗ {r['unit']}:{r.get('message', '')}")
return {"success": not fail, "message": f"完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}",
"total": len(results), "done": len(ok) - len(skip)}
if __name__ == "__main__":
print(run())
@@ -0,0 +1,894 @@
# -*- coding: utf-8 -*-
"""
@FileName: import_add.py
@Description: XQ0014 重庆社保系统增减员办理(新参保-增员)—— 单文件自包含版
与 XQ0008 联动:消费 8 号需求产出的《XX增员导入名单.xls》,逐参保单位登录
重庆人社政务平台(法人用户)完成增员导入。
流程:
1. 读取最新《XXXX年X月社保变更及增减名单及人数统计.xlsx》(文件名年月动态,取最新)
→ sheet「YYYYMM参保名单」(年月动态,表头第3行,H-AV 共41列)
2. 筛选:区域(Y列)=重庆 ∩ 参保类型(H列)=新参保 ∩ 办理状态(AP列)非空,按参保单位分组
3. 匹配 XQ0008 产出:新参保-增员/{参保单位}增员导入名单.xls(文件名规则同 generate_add)
4. 取账号:最新《*社保户头管理台账*.xlsx》→ sheet「YYYY年M月缴费比例」(年月动态,
表头1-2行合并)→ 数据行筛选 城市(D列)=重庆 ∩ 是否在用(E列)=是,
参保户头(B列)=参保单位 匹配:
用户名 = I列(统一社会信用代码) 优先,为空回退 K列(政务平台用户名),都空→预检报错
密码 = L列(政务平台密码),为空→预检报错
5. 预检汇总:所有单位「导入文件 + 账号 + 密码」齐备才继续,否则列出全部问题后停止
6. 逐参保单位登录政务平台(调用同目录 sb_login,每个单位登录一次,
不做 cookies 缓存——平台 cookies 极易失效,账号多各自缓存也无意义)
登录后的网页导入操作步骤
依赖安装:
pip install pandas openpyxl DrissionPage python-dotenv ddddocr
环境变量(可选):
cq_social_change_dir = 名单/产出根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
cq_social_ledger_dir = 台账目录(默认 D:\\资料\\人资\\社保系统增减员办理)
运行:python import_add.py
"""
import os
import re
import sys
import time
from glob import glob
from datetime import datetime
from pathlib import Path
# ---- 单文件运行支持:把本文件所在目录加入 sys.path,保证可独立运行并 import 同目录 sb_login ----
_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
try:
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
f"缺失依赖详情: {_import_err}")
# ==================== 1. 路径与筛选配置 ====================
SOURCE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
LEDGER_DIR = os.getenv("cq_social_ledger_dir") or r"D:\资料\人资\社保系统增减员办理"
IMPORT_DIR_NAME = "新参保-增员" # XQ0008 产出目录(按参保类型分文件夹)
SOURCE_GLOB = "*社保*.xlsx" # 源名单文件(年月动态,取最新)
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账文件(可能加前后缀,取最新)
REGION = "重庆" # 区域(Y列)筛选值
OPERATION_TYPE = "新参保" # 参保类型(H列)筛选值
TYPE_COL, REGION_COL, STATUS_COL, UNIT_COL = "参保类型", "区域", "办理状态", "参保单位"
# 台账「缴费比例」sheet 数据列(0-based,表头占 1-2 行已跳过):
LEDGER_COL = {"户头": 1, "城市": 3, "在用": 4, "信用代码": 8, "平台用户名": 10, "平台密码": 11}
DO_LOGIN = True # 预检通过后是否执行逐单位登录(网页操作步骤未补充前可置 False 只做预检)
RUN_LIMIT = None # 每次运行最多办理的单位数(None=不限制,一次跑完剩余全部;已办单位自动跳过)
DEBUG_MODE = False # 调试模式开关:开启后才保存页面截图(debug_shots\)和验证码截图(debug_captcha\),日常运行关闭
os.environ['sb_captcha_debug'] = '1' if DEBUG_MODE else '0' # 同步给 sb_login:控制验证码调试图是否落盘
# 记录本次使用的源名单(供网页操作后回写台账)
SOURCE_FILE_USED, SOURCE_SHEET_USED = None, None
# ==================== 2. 通用辅助 ====================
def _safe_name(value):
"""单位名转安全文件名(与 XQ0008 generate_add.py 规则一致,保证产出文件名可复现)。"""
if value is None or not str(value).strip():
return "未知单位"
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
if name.endswith("店"):
name = name[:-1]
return name
def _to_text(value):
"""None/NaN → '',其余转去空白字符串(台账号/密码列用)。"""
if value is None:
return ""
try:
if pd.isna(value):
return ""
except (TypeError, ValueError):
pass
if isinstance(value, float) and value.is_integer():
return str(int(value))
return str(value).strip()
def _latest_file(directory, pattern):
"""目录内按模式取最新文件(排除 Excel 临时文件 ~$)。"""
candidates = [p for p in glob(os.path.join(directory, pattern))
if not os.path.basename(p).startswith("~$")]
if not candidates:
raise FileNotFoundError(f"在 {directory} 下未找到匹配 {pattern} 的文件")
return max(candidates, key=os.path.getmtime)
def _pick_sheet(xl, exact_name, keyword, pattern=None):
"""优先精确 sheet 名,其次按关键字/正则匹配;正则匹配时取年月最新。"""
names = [n.strip() for n in xl.sheet_names]
if exact_name in names:
return exact_name
if pattern:
hits = [(int(m.group(1)), int(m.group(2)), n)
for n in names if (m := re.match(pattern, n))]
if hits:
return max(hits)[2]
for n in names:
if keyword in n:
return n
raise ValueError(f"未找到目标 sheet(精确={exact_name},关键字={keyword}),"
f"实际 sheets:{xl.sheet_names}")
# ==================== 3. 源名单读取与筛选 ====================
def _norm_id(v):
"""身份证号规范化:去空格、转大写;数值型(Excel 把纯数字身份证存成数值)转整数字符串。"""
if v is None:
return ''
if isinstance(v, float) and v.is_integer():
v = int(v)
return str(v).strip().upper()
def _id_hit(cid, ref_ids):
"""身份证匹配:规范化后精确匹配(去空格、转大写)。
不做前缀/模糊匹配:同一批人同区县同出生日期时前 15 位可能撞车,误匹配会回写错行。"""
return bool(cid) and cid in ref_ids
def load_units(exclude_ids=frozenset()):
"""读取源名单并筛选,返回 [(参保单位, 人数), ...](按单位分组)。
exclude_ids:需排除的身份证号集合(上次运行已回写办理状态的人员,防重复申报)。
"""
global SOURCE_FILE_USED, SOURCE_SHEET_USED
source_file = _latest_file(SOURCE_DIR, SOURCE_GLOB)
now = datetime.now()
xl = pd.ExcelFile(source_file)
sheet_name = _pick_sheet(xl, f"{now:%Y%m}参保名单", "参保名单")
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
SOURCE_FILE_USED, SOURCE_SHEET_USED = source_file, sheet_name
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
# 增员只办「办理状态为空/NULL」的行:待审核=已提交社保局,参保失败=已在其它流程处理,均跳过
status_text = df[STATUS_COL].astype(str).str.strip().str.lower()
mask = (
(df[REGION_COL].astype(str).str.strip() == REGION)
& (df[TYPE_COL].astype(str).str.strip() == OPERATION_TYPE)
& (df[STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
)
sub = df[mask].copy()
if exclude_ids and '身份证号码' in sub.columns:
before = len(sub)
ref = [_norm_id(x) for x in exclude_ids]
sub = sub[~sub['身份证号码'].map(lambda v: _id_hit(_norm_id(v), ref))]
dropped = before - len(sub)
if dropped:
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报)")
if sub.empty:
print(f"没有筛选到数据({REGION} ∩ {OPERATION_TYPE} ∩ 办理状态为空)")
return []
grouped = sub.groupby(sub[UNIT_COL].astype(str).str.strip()).size()
units = sorted(grouped.items(), key=lambda t: t[0])
print(f"筛选结果:共 {sum(n for _, n in units)} 人 / {len(units)} 个参保单位")
return units
# ==================== 4. 台账取号 ====================
def load_accounts(unit_names):
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
取不到的单位不在返回值中(由预检统一报错)。
"""
ledger_file = _latest_file(LEDGER_DIR, LEDGER_GLOB)
now = datetime.now()
xl = pd.ExcelFile(ledger_file)
sheet_name = _pick_sheet(xl, f"{now.year}年{now.month}月缴费比例", "缴费比例",
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
print(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
df = df[df[LEDGER_COL["户头"]].notna()].copy()
for c in LEDGER_COL.values():
df[c] = df[c].map(_to_text)
pool = df[(df[LEDGER_COL["城市"]] == REGION) & (df[LEDGER_COL["在用"]] == "是")]
accounts = {}
for name in unit_names:
hit = pool[pool[LEDGER_COL["户头"]] == name]
if hit.empty:
continue # 预检阶段统一报「台账未匹配」
row = hit.iloc[0]
credit, plat_user, plat_pwd = (
row[LEDGER_COL["信用代码"]], row[LEDGER_COL["平台用户名"]], row[LEDGER_COL["平台密码"]])
# 用户名规则:I列信用代码优先,空则回退 K列平台用户名
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
return accounts
# ==================== 5. 预检 ====================
def precheck(units, accounts):
"""预检:核对每个单位的导入文件与账号。返回待办列表 [{unit, count, file, username, password}]。"""
import_dir = os.path.join(SOURCE_DIR, IMPORT_DIR_NAME)
tasks, errors = [], []
print("\n========== 预检 ==========")
for unit, count in units:
file_path = os.path.join(import_dir, f"{_safe_name(unit)}增员导入名单.xls")
acc = accounts.get(unit)
problems = []
if not os.path.isfile(file_path):
problems.append(f"缺导入文件({IMPORT_DIR_NAME}\\{os.path.basename(file_path)})")
if acc is None:
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
else:
if not acc["username"]:
problems.append("账号缺失(I列信用代码与K列平台用户名均为空)")
if not acc["password"]:
problems.append("密码缺失(L列平台密码为空)")
if problems:
errors.append(f"[{unit}] " + ";".join(problems))
print(f" ✗ {unit}({count}人):{';'.join(problems)}")
else:
tasks.append({"unit": unit, "count": count, "file": file_path,
"username": acc["username"], "password": acc["password"]})
print(f" ✓ {unit}({count}人)账号={acc['username']}"
f"({acc['username_src']})文件={os.path.basename(file_path)}")
if errors:
print(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
for e in errors:
print(f" - {e}")
return None
print(f"预检通过:{len(tasks)} 个单位待办理\n")
return tasks
# ==================== 6. 网页操作:城保参保单位人员增加 ====================
BUSINESS_ITEM = "城保参保单位人员增加" # 单位办事列表里的业务名称
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
DEBUG_SHOT_DIR = _HERE / "debug_shots"
def _shot(tab, name):
"""调试截图:仅 DEBUG_MODE 开启时保存页面截图并打印当前 URL,便于事后定位哪一步页面状态异常。"""
if not DEBUG_MODE:
return
try:
DEBUG_SHOT_DIR.mkdir(exist_ok=True)
ts = datetime.now().strftime("%H%M%S")
tab.get_screenshot(path=str(DEBUG_SHOT_DIR), name=f"{ts}_{name}.png")
print(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
except Exception as e:
print(f" [截图失败] {name}: {e}")
def _click_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序定位并点击第一个命中元素,全部未命中抛异常。"""
last_err = None
for sel in selectors:
try:
ele = tab.ele(sel, timeout=timeout)
except Exception as e:
last_err = e
continue
if ele:
ele.click()
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}({last_err})")
def _find_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序查找元素,全部未命中抛异常。"""
for sel in selectors:
ele = tab.ele(sel, timeout=timeout)
if ele:
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}")
def _wait_modal(tab, keyword, timeout=60):
"""等待某 ant-modal 弹窗正文出现指定关键字,返回该弹窗元素;超时返回 None。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for m in tab.eles('css:.ant-modal-body'):
if keyword in (m.text or ''):
return m
except Exception:
pass
time.sleep(0.5)
return None
def _dismiss_popups(tab, rounds=5):
"""循环关闭常见提示弹窗(我已知晓/我知道了/确定/同意),直到没有可关的。"""
texts = ["我已知晓", "我知道了", "知道了", "确 定", "确定", "同 意", "同意"]
for _ in range(rounds):
hit = False
for t in texts:
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=0.5)
except Exception:
btn = None
if btn:
try:
btn.click()
print(f" 关闭弹窗:{t}")
hit = True
time.sleep(1.2)
except Exception:
pass
if not hit:
break
def _open_business_page(page, work_tab):
"""工作台 → 单位办事 → 「城保参保单位人员增加」在线办理。返回承载业务页的 tab。"""
before = set(page.tab_ids)
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
time.sleep(2.5)
# 列表项:h4 标题定位 → 上溯到 li.ant-list-item → 点其「在线办理」
h4 = _find_any(work_tab, [f'tag:h4@@text()={BUSINESS_ITEM}'], f'业务入口「{BUSINESS_ITEM}」')
li = h4
for _ in range(6):
li = li.parent()
if li is None:
break
if li.tag == 'li':
break
act = li.ele('text=在线办理', timeout=3) if li is not None else None
if act is None:
raise RuntimeError("网页操作失败:找不到「在线办理」按钮")
act.click()
# 业务页可能新开 tab 或当前页跳转:轮询识别出现上传控件(input[type=file])的页面
deadline = time.time() + 30
while time.time() < deadline:
time.sleep(1)
cand_tids = [i for i in page.tab_ids if i not in before] + [work_tab.tab_id]
for tid in cand_tids:
try:
t = page.get_tab(tid)
if t.ele('#customized_form_controls_data', timeout=0.5):
return t
except Exception:
continue
raise RuntimeError("进入在线办理页失败(未出现文件上传控件)")
def _wait_import_result(tab, timeout=90):
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示(modal/toast,不限语言)。
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
# 1) modal:含「导入完成」即成功;其它任何非加载中文本都视为失败提示(如 Required request part ... 报错)
for m in tab.eles('css:.ant-modal-body'):
t = (m.text or '').strip()
if '导入完成' in t:
return "ok", m
if t and not any(k in t for k in ('提交中', '导入中', '加载中')):
return "fail", t
# 2) 顶部 toast 小提示(几秒即消失,需轮询抓),任何非空文本都记录
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
return "fail", t
except Exception:
pass
time.sleep(0.4)
return "timeout", None
def _wait_unit_ready(tab, timeout=5):
"""等参保单位信息真正显示出来(导入请求 aab001 部件的就绪信号)。
单位信息由上传文件解析而来,显示在 borderless 下拉框里:
可能先以 placeholder 形式出现(如「20389605,重庆XX有限公司」),也可能直接是选中值。
必须等文本内容真正渲染出来(非空)才算就绪,仅元素挂载不算。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for sel in tab.eles('css:.ant-select-borderless'):
for kind in ('css:.ant-select-selection-placeholder',
'css:.ant-select-selection-item'):
ele = sel.ele(kind, timeout=1)
# 元素存在且文本可见(如「20389605,重庆XX有限公司」)才代表单位信息已显示
if ele and (ele.text or '').strip():
return True
except Exception:
pass
time.sleep(0.5)
return False
def _upload_import(tab, xls_path, max_rounds=3):
"""上传名单 xls 并点「导入」,带失败探针与重试:
每轮都重新选文件(重新触发页面解析单位信息),就绪后再点导入。
返回 (导入成功人数, 导入失败人数)。"""
last_err = "导入超时无响应"
for rnd in range(1, max_rounds + 1):
inp = _find_any(tab, ['#customized_form_controls_data',
'css:input[type="file"]'], '文件上传控件')
inp.input(xls_path) # DrissionPage 对 file input 直接写路径即上传
# 等单位信息出现(placeholder 或选中值),未就绪点导入会报 aab001 缺失
if not _wait_unit_ready(tab, timeout=40):
print(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
time.sleep(1.0) # 就绪后再留缓冲,避免点太快
_shot(tab, "03_file_selected")
_click_any(tab, ['tag:button@@text()=导 入', 'tag:button@@text():导入'], '「导 入」按钮')
state, payload = _wait_import_result(tab, timeout=90)
if state == "ok":
_shot(tab, "04_import_result")
text = payload.text or ''
m_ok = re.search(r'成功[::]\s*(\d+)\s*人', text)
m_fail = re.search(r'失败[::]\s*(\d+)\s*人', text)
total = int(m_ok.group(1)) if m_ok else 0
failed = int(m_fail.group(1)) if m_fail else 0
print(f" 导入完成:成功 {total} 人,失败 {failed} 人")
if total == 0:
raise RuntimeError(f"导入完成但成功人数为 0,提示:{text.strip()[:120]}")
for t in ('确 定', '确定'):
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
except Exception:
btn = None
if btn:
btn.click()
break
time.sleep(1.5)
return total, failed
# 失败/超时:记录提示,重试
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
print(f" 第 {rnd} 轮导入未成功:{str(last_err)[:120]}")
time.sleep(2 + rnd) # 失败后多等一会,避免连点触发风控
raise RuntimeError(f"导入重试 {max_rounds} 轮均失败,最后提示:{str(last_err)[:160]}")
def _read_failed_rows(tab):
"""切到「校验未通过人员」tab 读表格,返回 [(证件号码, 详细信息), ...]。
按表头(含「证件号码」+「详细信息」列)定位表格,避免抓到左侧导航等其它 tab 组件的面板。"""
try:
tab_btn = tab.ele('tag:span@@text()=校验未通过人员', timeout=10)
except Exception:
tab_btn = None
if not tab_btn:
return []
tab_btn.click()
time.sleep(2)
rows = []
try:
for tb in tab.eles('tag:table'):
ths = [th.text.strip() for th in tb.eles('tag:th')]
if '证件号码' in ths and '详细信息' in ths:
i_id, i_detail = ths.index('证件号码'), ths.index('详细信息')
for tr in tb.eles('css:tbody tr'):
tds = [td.text.strip() for td in tr.eles('tag:td')]
if len(tds) > max(i_id, i_detail) and len(tds[i_id]) >= 15:
detail = tds[i_detail]
# 备注只保留冒号后的内容(去掉"校验通过业务校验失败:"这类前缀)
for sep in (':', ':'):
if sep in detail:
detail = detail.split(sep, 1)[1].strip()
break
rows.append((tds[i_id], detail))
break
except Exception as e:
print(f" 读取校验未通过表格异常:{e}")
_shot(tab, "05_check_failed_tab")
return rows
def _wait_pdf_ready(tab, timeout=60):
"""等 react-pdf canvas 出现且 2 秒不变,视为 PDF 绘制完成。超时仅告警不拦截。"""
last, stable_since = None, None
deadline = time.time() + timeout
while time.time() < deadline:
try:
canvases = tab.eles('css:.react-pdf__Page__canvas')
sig = (len(canvases), canvases[0].attr('width') if canvases else None)
except Exception:
sig = None
if sig and sig[0] > 0:
if sig == last:
if stable_since and time.time() - stable_since >= 2:
return True
else:
stable_since = time.time()
last = sig
time.sleep(1)
print(" 警告:等待 PDF 渲染超时,继续尝试提交")
return False
def _goto_submit_page(tab, tries=3):
"""点「下一步」进入提交页,验证「提 交」按钮出现;未出现则重试。"""
for i in range(tries):
_click_any(tab, ['tag:button@@text()=下一步'], '「下一步」按钮')
deadline = time.time() + 12
while time.time() < deadline:
if tab.ele('tag:button@@text()=提 交', timeout=1):
return True
time.sleep(0.5)
print(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
time.sleep(1.5)
return False
def _click_submit(tab, tries=3):
"""点「提 交」,验证「已知晓」确认弹窗出现;第一次可能因按钮未就绪失效,重试。
期间打印页面 toast 提示,便于诊断失败原因。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
deadline = time.time() + 10
while time.time() < deadline:
if tab.ele('tag:button@@text()=已知晓', timeout=1):
return True
try:
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
print(f" 提交提示:{t[:100]}")
except Exception:
pass
time.sleep(0.5)
print(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
time.sleep(1.5)
return False
def _confirm_submit(tab, tries=3):
"""点「已知晓」→ 等「您已成功提交」弹窗;未出现则重点已知晓。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=已知晓', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
if _wait_modal(tab, '您已成功提交', timeout=60):
return True
print(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
return False
def _predeclare_and_submit(page, tab):
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交(带重试)→ 已知晓 → 等成功。"""
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
if _wait_modal(tab, '预申报成功', timeout=60) is None:
raise RuntimeError("预申报后未出现成功弹窗")
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
# 等申报页就绪:提示弹窗或「全部提交」按钮任一出现即继续(替代固定 sleep,省 ~8s 空等)
deadline = time.time() + 15
while time.time() < deadline:
try:
if tab.ele('tag:button@@text()=我已知晓', timeout=0.5) or \
tab.ele('tag:button@@text()=我知道了', timeout=0.5) or \
tab.ele('tag:button@@text()=全部提交', timeout=0.5):
break
except Exception:
pass
time.sleep(0.3)
_dismiss_popups(tab) # 系统提示「我已知晓」+ 操作说明「我知道了」
_shot(tab, "06_declare_page")
_click_any(tab, ['tag:button@@text()=全部提交'], '「全部提交」按钮')
_wait_pdf_ready(tab)
_shot(tab, "07_pdf_ready")
if not _goto_submit_page(tab):
_shot(tab, "08_no_submit_btn")
raise RuntimeError("点击下一步后未出现「提 交」按钮")
_shot(tab, "08_submit_page")
if not _click_submit(tab):
_shot(tab, "09_submit_no_confirm")
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
if not _confirm_submit(tab):
_shot(tab, "10_confirm_no_success")
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
_shot(tab, "11_submit_success")
print(" 提交成功")
def _collect_review_rows(tab):
"""从明细表收集审核结论:{证件号码: (审核结论, 业务流水号)}。"""
results = {}
for tr in tab.eles('css:.ant-table-tbody tr.ant-table-row'):
try:
tds = [td.text.strip() for td in tr.eles('tag:td')]
except Exception:
continue
# 明细表结构:业务流水号/业务类型/姓名/证件号码/审核结论/审核意见/操作
# 证件号码可能是 15/18 位,尾号可为 X,不能只 isdigit
cid = tds[3] if len(tds) > 3 else ''
if len(cid) in (15, 18) and cid.rstrip('Xx').isdigit():
results[cid] = (tds[4], tds[0])
return results
def _open_query_page(page, tab, timeout=25):
"""点「去查看」进入申报查询列表(可能新开 tab),返回承载列表的 tab。"""
before = set(page.tab_ids)
_click_any(tab, ['tag:button@@text()=去查看'], '「去查看」按钮')
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(1)
tids = [i for i in page.tab_ids if i not in before] + [tab.tab_id]
for tid in tids:
try:
t = page.get_tab(tid)
row = t.ele('css:.ant-table-tbody tr.ant-table-row', timeout=0.5)
if row and row.ele('tag:a@@text()=查看', timeout=0.5):
_shot(t, "12_query_list")
return t
except Exception:
continue
raise RuntimeError("点击去查看后未找到申报查询列表(含「查看」按钮的记录表)")
def _query_review_results(page, tab):
"""进入申报查询列表 → 打开序号1记录的「查看」→ 读明细表审核结论。
返回 {证件号码: (审核结论, 业务流水号)}。"""
qtab = _open_query_page(page, tab)
for attempt in range(3):
row = qtab.ele('css:.ant-table-tbody tr.ant-table-row', timeout=10)
view = row.ele('tag:a@@text()=查看', timeout=3) if row else None
if view:
try:
view.click()
except Exception:
pass
# 等明细表出现(含 18 位证件号码的行)
deadline = time.time() + 12
while time.time() < deadline:
time.sleep(1)
results = _collect_review_rows(qtab)
if results:
_shot(qtab, "13_review_detail")
return results
print(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
_shot(qtab, "13_review_detail_miss")
time.sleep(1.5)
raise RuntimeError("未读取到审核结论明细表")
# ==================== 6b. 台账回写(JSON 缓存防崩溃,运行结束统一回写 Excel 一次) ====================
# 每个账号办完:回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel);
# 运行结束时 flush_writeback 统一写 Excel 一次,保存成功校验后删除缓存;
# 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单。
_PENDING_STATUS, _PENDING_REMARK = {}, {}
_CKPT_FILE = _HERE / "writeback_pending.json"
def _save_ckpt():
"""把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。"""
import json
data = [{"id": cid, "status": _PENDING_STATUS.get(cid, ""),
"remark": _PENDING_REMARK.get(cid, "")}
for cid in dict.fromkeys(list(_PENDING_STATUS) + list(_PENDING_REMARK))]
tmp = _CKPT_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(_CKPT_FILE)
def _load_ckpt():
"""启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。"""
recovered = set()
if not _CKPT_FILE.exists():
return recovered
try:
import json
for it in json.loads(_CKPT_FILE.read_text(encoding="utf-8")):
cid = it.get("id")
if it.get("status"):
_PENDING_STATUS[cid] = it["status"]
if it.get("remark"):
_PENDING_REMARK[cid] = it["remark"]
if cid:
recovered.add(cid)
return recovered
except Exception as e:
print(f" 恢复回写缓存失败:{e}")
return recovered
def writeback_source(status_map, remark_map):
"""按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel):
status_map {身份证: 办理状态};remark_map {身份证: 备注}。"""
_PENDING_STATUS.update(status_map or {})
_PENDING_REMARK.update(remark_map or {})
try:
_save_ckpt()
except Exception as e:
print(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}")
def flush_writeback():
"""把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件),
保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。"""
if not (_PENDING_STATUS or _PENDING_REMARK):
return
if not SOURCE_FILE_USED:
raise RuntimeError("无源名单文件记录,无法回写")
from openpyxl import load_workbook
wb = load_workbook(SOURCE_FILE_USED)
ws = wb[SOURCE_SHEET_USED]
# 表头第3行定位列号
hdr = {}
for c in ws[3]:
if c.value is not None:
hdr[str(c.value).strip()] = c.column
col_id = hdr.get('身份证号码')
col_status = hdr.get('办理状态')
col_remark = hdr.get('备注')
if not col_id or not col_status:
raise RuntimeError(f"源名单缺少身份证号码/办理状态列,无法回写")
changed = 0
pending_ids = set(_PENDING_STATUS) | set(_PENDING_REMARK)
ref = [_norm_id(x) for x in pending_ids]
for row in ws.iter_rows(min_row=4):
cid = _norm_id(row[col_id - 1].value)
if cid and _id_hit(cid, ref):
r = row[0].row
if cid in _PENDING_STATUS:
ws.cell(row=r, column=col_status, value=_PENDING_STATUS[cid])
if cid in _PENDING_REMARK and col_remark:
# 备注追加不覆盖:读取原单元格内容,新备注换行追加在后面(已存在则不重复追加)
cell = ws.cell(row=r, column=col_remark)
old = str(cell.value or '').strip()
new = str(_PENDING_REMARK[cid]).strip()
if new in old:
pass # 重查场景:备注已写过,跳过防重复
else:
cell.value = f"{old}\n{new}" if old else new
changed += 1
try:
wb.save(SOURCE_FILE_USED)
except PermissionError:
# 缓存保留,下次启动自动恢复回写
raise RuntimeError("源名单文件被占用(请关闭 Excel 后重跑),回写未保存")
_PENDING_STATUS.clear()
_PENDING_REMARK.clear()
if _CKPT_FILE.exists():
_CKPT_FILE.unlink()
print(f" 源名单回写完成:更新 {changed} 行 → {os.path.basename(SOURCE_FILE_USED)}(缓存已清除)")
print(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP),"
"下次运行前请先用 Excel 打开并保存一次该名单以重算公式")
# ==================== 6c. 单个单位完整网页操作 ====================
def do_web_import(task):
"""登录后的完整业务流程:进业务页 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。
返回结果 dict(JSON 安全)。"""
import sb_login
page = sb_login.LAST_SESSION.get('page')
work_tab = sb_login.LAST_SESSION.get('tab')
if page is None or work_tab is None:
return {"success": False, "message": "无有效登录会话"}
res = {"success": False, "imported": 0, "failed": [], "review": {}}
try:
_shot(work_tab, "01_workbench")
biz_tab = _open_business_page(page, work_tab)
_shot(biz_tab, "02_biz_upload_page")
# 1) 上传导入
total, _failed_cnt = _upload_import(biz_tab, task['file'])
res['imported'] = total
# 2) 校验未通过:回写 参保失败 + 备注(详细信息)
# 账目规则:弹窗「成功N人」+「校验未通过人员」= 名单人数,不平账中止防止漏人导致下次重复申报
fail_rows = _read_failed_rows(biz_tab)
res['failed'] = [{"id": cid, "detail": d} for cid, d in fail_rows]
expected = task.get('count', 0)
if expected and total + len(fail_rows) != expected:
raise RuntimeError(
f"人数不平账:导入成功{total} + 校验未通过{len(fail_rows)} ≠ 名单{expected}人,"
f"中止该单位(防漏人/重复申报),请人工核对")
if fail_rows:
writeback_source({cid: "参保失败" for cid, _ in fail_rows},
{cid: d for cid, d in fail_rows})
passed = total
# 3) 全员未通过 → 跳过申报
if passed <= 0:
print(" 校验通过人数为 0,跳过申报")
res.update(success=True, message=f"导入{total}人,全部校验未通过,已回写未申报")
return res
# 4) 预申报 → 正式提交 → 查询审核结论回写
_predeclare_and_submit(page, biz_tab)
review = _query_review_results(page, biz_tab)
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
for cid, (c, sn) in review.items()]
if review:
writeback_source({cid: concl for cid, (concl, _) in review.items()}, {})
res.update(success=True,
message=f"导入{total}人,未通过{len(fail_rows)}人,提交{passed}人")
return res
except Exception as e:
res["message"] = f"网页操作异常:{e}"
return res
# ==================== 7. 逐单位登录 + 网页操作 ====================
def process_units(tasks):
"""逐参保单位:登录政务平台 → 完整网页导入申报 → 回写。
每个账号办完(无论成败)都清 cookies 关浏览器,下个账号全新开始。
回写策略:单位内累积到内存并写 JSON 缓存(防崩溃),运行结束统一回写 Excel 一次。"""
import sb_login
results = []
for i, task in enumerate(tasks, 1):
print(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人)==========")
print(f"导入文件:{task['file']}")
try:
login_res = sb_login.main({"username": task["username"], "password": task["password"]})
except Exception as e:
login_res = {"success": False, "message": f"登录调用异常:{e}"}
print(f"登录结果:{login_res.get('message')}")
try:
if login_res.get("success"):
web_res = do_web_import(task)
print(f"办理结果:{web_res.get('message')}")
results.append({**task, **web_res})
else:
results.append({**task, "success": False,
"message": login_res.get("message", "")})
finally:
# 账号隔离:清 cookies + 关浏览器,再进入下一单位
sb_login.close_session()
return results
# ==================== 8. 主流程 ====================
def run():
"""主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录(+导入)→ 统一回写。
返回 JSON 安全 dict。"""
recovered_ids = _load_ckpt()
units = load_units(exclude_ids=recovered_ids)
# 崩溃恢复:上次运行残留的回写缓存统一落盘(排除逻辑已在 load_units 中生效,
# 即使下面回写失败,这些人也不会被当成待办重复申报)
if recovered_ids:
print("\n检测到上次未回写的内容,先统一回写:")
try:
flush_writeback()
except Exception as e:
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
if not units:
return {"success": True, "message": "无待办数据", "total": 0, "done": 0}
accounts = load_accounts([u for u, _ in units])
tasks = precheck(units, accounts)
if tasks is None:
return {"success": False, "message": "预检未通过,详见日志", "total": len(units), "done": 0}
if not DO_LOGIN:
print("DO_LOGIN=False,仅完成预检,跳过登录")
return {"success": True, "message": "预检通过(未登录)", "total": len(tasks), "done": 0}
results = process_units(tasks[:RUN_LIMIT])
# 运行结束:本次累积的回写内容统一写 Excel 一次(失败则 JSON 缓存保留,下次启动恢复)
try:
flush_writeback()
except Exception as e:
print(f"回写失败:{e}")
ok = [r for r in results if r["success"]]
fail = [r for r in results if not r["success"]]
print(f"\n========== 汇总 ==========")
print(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
for r in fail:
print(f" ✗ {r['unit']}:{r.get('message', '')}")
return {"success": not fail, "message": f"成功{len(ok)}/失败{len(fail)}",
"total": len(results), "done": len(ok)}
if __name__ == "__main__":
print(run())
@@ -0,0 +1,597 @@
# -*- coding: utf-8 -*-
"""
@FileName: sb_login.py
@Description: 重庆人社网上服务大厅(政务平台)法人登录模块 —— XQ0014 专用(不共享)。
每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务。
不做 cookies 缓存:政务平台 cookies 极易失效,缓存无意义;账号多,各自缓存也冗余,
统一每次现场真登录(浏览器走完整 SSO 流程 + ddddocr 识别图形验证码)。
登录流程(与 aa.md 步骤一致):
1. 打开办事大厅页面 → 等待登录入口出现;
2. 点击「登录」→ 跳转新 tab 到 SSO(authcq.cqdcg.com:1443/sso/login);
3. 切换「法人用户」tab;
4. 输入账号(统一社会信用代码或政务平台用户名)+ 密码;
5. 元素截图截取图形验证码(base64 内嵌 PNG)→ ddddocr 识别 → 输入验证码;
6. 点击「登 录」→ 等待跳回办事大厅域名即成功;
7. 识别失败自动刷新验证码重试(验证码 5 次/轮 × 流程 3 轮)。
配置(可选,仅作为 main() 未传账号时的默认值):
sb_login_username=默认账号;sb_login_password=默认密码
sb_captcha_debug_dir=(可选)验证码调试图片输出目录;不设置则不落盘
依赖(影刀「Python包管理」安装):
pip install DrissionPage requests python-dotenv ddddocr
入口:
main(args) 影刀指令/流程调用入口,args 传 {"username": 账号, "password": 密码},
返回 JSON 安全 dict {success, username, message}
python sb_login.py 独立运行(用 .env 默认账号做登录自测)
"""
import os
import time
import random
import base64
from DrissionPage import ChromiumPage, ChromiumOptions
from dotenv import load_dotenv
# ================== 配置 ==================
# 默认账号只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文;
# XQ0014 主流程会按参保单位从台账取号后通过 main(args) 传入,这里仅作独立运行兜底。
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
# 验证码调试图片:默认落盘到本目录 debug_captcha\(排查识别率用),可用 sb_captcha_debug_dir 覆盖
# 落盘开关:环境变量 sb_captcha_debug(1/0),默认关闭;由 import_add 的 DEBUG_MODE 统一控制
CAPTCHA_DEBUG_DIR = os.getenv('sb_captcha_debug_dir', '').strip() or os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'debug_captcha')
CAPTCHA_DEBUG = os.getenv('sb_captcha_debug', '0').strip().lower() in ('1', 'true', 'yes', 'on')
RETRY_MAX = 5 # 验证码最大重试次数(每轮)
FLOW_RETRY = 3 # 整个登录流程最大轮数
TIMEOUT = 10 # 元素等待超时(秒)
HEADLESS = False
HUMAN_DELAY = (0.4, 1.2) # 操作间随机延时区间(秒),模拟人工降低脚本特征
def ensure_dir(path):
if path:
os.makedirs(path, exist_ok=True)
# ================== 影刀全局变量 ==================
def _set_login_state(value):
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
try:
glv['login_state'] = value
print(f"已写入影刀全局变量 login_state={value}")
except Exception as e:
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
# ================== 验证码识别(元素截图 + 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):
"""可选:落盘验证码调试图片(仅 CAPTCHA_DEBUG 开启时),便于分析识别失败样本。"""
if not CAPTCHA_DEBUG or not CAPTCHA_DEBUG_DIR:
return
try:
ensure_dir(CAPTCHA_DEBUG_DIR)
path = os.path.join(CAPTCHA_DEBUG_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:
print(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()
print(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 _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——跳转链中间页(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 后刷新重试一次
print("未找到登录入口(可能残留上一账号登录态),清除 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:
# 首页已是登录态(无登录入口):提示需清登录态,由调用方处理
print("找不到登录入口(首页可能已是登录态)")
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):
print(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
print("点击登录后未检测到就绪的 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:
print("找不到账号输入框")
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:
print("找不到密码输入框")
return False
pwd_input.clear()
pwd_input.input(password)
_human_pause()
# 图形验证码:base64 内嵌图(从验证码输入框容器定位,避免抓到页面其它图标)
for attempt in range(RETRY_MAX):
print(f"--- 第 {retry_index}-{attempt + 1} 次验证码识别 ---")
img, code_input = _find_captcha(tab)
if not img or not code_input:
print("找不到验证码图片或输入框")
return False
img_bytes = _read_img_bytes(img)
if not img_bytes:
print("验证码图数据为空")
time.sleep(1)
continue
try:
code = _recognize_captcha(img_bytes)
except Exception as e:
print(f"ddddocr 识别异常:{e}")
return False
print(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:
print("找不到登录提交按钮")
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):
print(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:
print(f"登录成功,已跳转:{url}")
_dismiss_notice(tab)
return True, tab
# ant-message 错误提示(验证码错误/账号密码错误等)
try:
err = tab.ele('css:.ant-message-error', timeout=0.5)
if err:
print(f"登录失败提示:{err.text}")
return False, None
except Exception:
pass
print("等待登录结果超时")
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 还没变,再点一次
print("警告:验证码图片刷新后未变化")
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:
print(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:
# 元素失效/页面刷新等异常:不中断整体流程,进入下一轮
print(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}")
time.sleep(1)
print("登录失败(验证码识别未通过或流程异常)")
return _finish(False)
except Exception:
# 整体异常也要保证清理(失败场景不留会话)
_teardown(page)
raise
def ensure_login(username=None, password=None):
"""
以指定账号现场登录政务平台(无缓存,每次真登录)。
返回 JSON 安全 dict:{success, username, message}
"""
_set_login_state(False)
# 未传账号时回落到 .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": "登录账号/密码缺失(main 未传参且 .env 未配置 sb_login_username / sb_login_password)"}
ok, _work_tab = _do_login(username, password)
if ok:
_set_login_state(True)
return {"success": True, "username": username, "message": "登录成功"}
return {"success": False, "username": username,
"message": "登录失败(验证码识别未通过或流程异常)"}
# ================== 调用入口 ==================
def main(args):
"""
影刀指令/流程调用入口。
args: dict,{"username": 账号(必填,统一社会信用代码或政务平台用户名),
"password": 密码(必填)}
返回: dict {success, username, message}
"""
if not args:
args = {}
try:
return ensure_login(args.get("username"), args.get("password"))
except Exception as e:
_set_login_state(False)
return {"success": False, "username": args.get("username", ''),
"message": f"登录过程异常:{e}"}
if __name__ == "__main__":
result = main({})
print("最终结果:", result)