1. 重构ehr/common/config.py与employer_insurance/config.py,新增多类别配置与工具函数 2. 重写employer_insurance.py,支持按类别调度处理 3. 新增影刀共享模块与业务脚本,统一RPA开发规范 4. 移除旧版冗余的影刀脚本文件
819 lines
32 KiB
Python
819 lines
32 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: roster_export.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-13
|
||
@Description: 雇主险花名册导出(影刀版,单文件自包含)——HR 登录(滑块验证码)
|
||
-> 进入花名册页 -> 组织机构(集团) -> 在职状态=在职 -> 更多操作 -> 自定义导出
|
||
-> 选择模板「雇主险增减员导出模板」-> 确认导出 -> 下载并按统一格式保存到
|
||
D:\资料\人资\雇主险\员工花名册.xlsx
|
||
@Version: 1.0.0
|
||
|
||
场景定位(雇主险流程第一步:导出花名册):
|
||
- 本文件是雇主险场景影刀版的第一步,输出后续「筛选复制」(roster_filter)所需的源表。
|
||
- 雇主险增减员只需「在职」人员,导出模板为「雇主险增减员导出模板」。
|
||
|
||
设计说明(避免维护 app/影刀两套版本,与 yingdao 下其它单文件版一致):
|
||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||
- 内含 HR 登录(滑块验证码识别),保证花名册导出所需的 hr.37du.co 登录态。
|
||
- 输出统一规范:单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
|
||
(与 app 版 roster_export._merge_roster_files 输出一致,供后续筛选复制直接读取)。
|
||
|
||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||
pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python numpy Pillow
|
||
|
||
环境变量(.env 文件或系统变量):
|
||
HR 登录:hr_login_username / hr_login_password(必须)
|
||
可选:
|
||
roster_template=雇主险增减员导出模板 自定义导出模板名(默认雇主险模板)
|
||
roster_statuses=在职 需导出的在职状态(逗号分隔,默认仅在职)
|
||
roster_output_path= 合并后源表保存路径(默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx)
|
||
roster_download_dir= 浏览器下载临时目录(默认 D:\\资料\\人资\\员工花名册)
|
||
|
||
运行:直接执行本文件即可导出花名册(无需命令行参数)
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
import functools
|
||
import json
|
||
import os
|
||
import random
|
||
import re
|
||
import time
|
||
|
||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||
try:
|
||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||
from dotenv import load_dotenv
|
||
import pandas as pd
|
||
import cv2
|
||
import numpy as np
|
||
except ImportError as _import_err:
|
||
raise RuntimeError(
|
||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||
"请先执行安装:\n"
|
||
" pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python "
|
||
"numpy Pillow\n"
|
||
f"缺失依赖详情: {_import_err}"
|
||
)
|
||
|
||
|
||
# ==================== 日志(print 替代 logging) ====================
|
||
class _PrintLogger:
|
||
def debug(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def info(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def warning(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def error(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
|
||
logger = _PrintLogger()
|
||
|
||
|
||
# ==================== 路径 & 常量配置 ====================
|
||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation\EmployerInsurance(影刀版独立子目录)
|
||
_APP_DATA_DIR = os.path.join(
|
||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||
'37duAutomation', 'EmployerInsurance'
|
||
)
|
||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||
COOKIE_FILE_HR = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||
|
||
# ---------- HR 系统 ----------
|
||
HR_BASE_URL = "https://hr.37du.co"
|
||
HR_LOGIN_URL = f"{HR_BASE_URL}/RedseaPlatform/"
|
||
HR_SUCCESS_KEYWORD = f"{HR_BASE_URL}/RedseaPlatform/PtPortal.mc?method=classic"
|
||
|
||
# ---------- 花名册自定义导出页面(aa.md 提供,与 app 版 ehr/common/config 一致) ----------
|
||
ROSTER_URL = (
|
||
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||
"#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311"
|
||
"|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/"
|
||
"getCustomCommonList.mc?clickFlag=true&treePermitType=permit"
|
||
"&useSealTreeData=0&menuName=%E5%91%98%E5%B7%A5%E8%8A%B1%E5%90%8D%E5%86%8C"
|
||
)
|
||
|
||
# ---------- 雇主险场景参数(可用环境变量/命令行覆盖) ----------
|
||
DEFAULT_TEMPLATE = "雇主险增减员导出模板"
|
||
DEFAULT_STATUSES = ["在职"]
|
||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\雇主险\员工花名册.xlsx"
|
||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\员工花名册"
|
||
|
||
# ---------- 流程步骤文案(与 app 版 roster_export 一致) ----------
|
||
TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树
|
||
TREE_GROUP = "集团" # 组织树根节点
|
||
BTN_MORE = "更多操作" # 更多操作按钮
|
||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||
TEMPLATE_PLACEHOLDER = "请选择模板"
|
||
BTN_CONFIRM = "确认导出"
|
||
FILTER_XPATH = 'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="筛选"]'
|
||
|
||
# ---------- 通用等待秒数 ----------
|
||
WAIT_SHORT = 0.6
|
||
WAIT_MID = 2.0
|
||
WAIT_LONG = 4.0
|
||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||
|
||
# ---------- HR 登录配置 ----------
|
||
LOGIN_BTN = "@id=login-btn"
|
||
ACCOUNT_INPUT_HR = "@id=j_username"
|
||
PASSWORD_INPUT_HR = "@id=j_password_2"
|
||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||
SLIDER_BTN = ".:v_rightBtn"
|
||
BG_IMG = ".imgBg"
|
||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||
HR_RETRY_MAX = 5
|
||
HR_TIMEOUT = 10
|
||
HR_HEADLESS = False
|
||
|
||
|
||
# ==================== 重试装饰器 ====================
|
||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||
if max_attempts < 1:
|
||
raise ValueError("max_attempts must be >= 1")
|
||
|
||
def decorator(func):
|
||
@functools.wraps(func)
|
||
def wrapper(*args, **kwargs):
|
||
last_exc = None
|
||
for attempt in range(1, max_attempts + 1):
|
||
try:
|
||
return func(*args, **kwargs)
|
||
except no_retry_on:
|
||
raise
|
||
except Exception as e:
|
||
last_exc = e
|
||
if attempt >= max_attempts:
|
||
logger.error("%s 连续 %d 次尝试失败: %s", func.__name__, max_attempts, e)
|
||
break
|
||
delay = 1.0 * (2.0 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||
logger.warning("%s 第 %d 次失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||
time.sleep(delay)
|
||
raise last_exc
|
||
return wrapper
|
||
return decorator
|
||
|
||
|
||
# ==================== Cookies 持久化 ====================
|
||
def _ensure_dir(path):
|
||
os.makedirs(path, exist_ok=True)
|
||
|
||
|
||
def save_browser_cookies(browser_page, path):
|
||
cookies = browser_page.cookies(all_domains=True)
|
||
if not cookies:
|
||
logger.warning("未获取到 Cookies,跳过保存")
|
||
return
|
||
_ensure_dir(os.path.dirname(path))
|
||
with open(path, 'w', encoding='utf-8') as f:
|
||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||
|
||
|
||
def load_cookies(path):
|
||
if not os.path.exists(path):
|
||
return None
|
||
with open(path, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
return cookies or None
|
||
|
||
|
||
# ==================== HR 登录(滑块验证码) ====================
|
||
def match_slider_dual(bg_bytes, slider_bytes):
|
||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||
if bg_img is None or slider_color is None:
|
||
raise RuntimeError("无法解码验证码图片")
|
||
|
||
bg_h, bg_w = bg_img.shape[:2]
|
||
x_offset, y_offset = 0, 0
|
||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||
alpha = slider_color[:, :, 3]
|
||
slider_rgb = slider_color[:, :, :3]
|
||
ys, xs = np.where(alpha > 0)
|
||
if len(ys) > 0:
|
||
y_min, y_max = np.min(ys), np.max(ys)
|
||
x_min, x_max = np.min(xs), np.max(xs)
|
||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||
x_offset, y_offset = x_min, y_min
|
||
else:
|
||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||
|
||
s_h, s_w = slider_rgb.shape[:2]
|
||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||
|
||
candidates = []
|
||
temp_result = result.copy()
|
||
for _ in range(6):
|
||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||
if max_val < 0.03:
|
||
break
|
||
candidates.append((max_val, max_loc))
|
||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||
temp_result[y0:y1, x0:x1] = -2.0
|
||
|
||
if not candidates:
|
||
raise RuntimeError("无有效滑块候选")
|
||
|
||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||
|
||
def region_whiteness(x, y, w, h):
|
||
roi = bg_img[y:y + h, x:x + w]
|
||
if roi.size == 0:
|
||
return 0.0
|
||
return float(np.all(roi > 200, axis=2).mean())
|
||
|
||
scored = []
|
||
for val, loc in candidates:
|
||
x, y = loc
|
||
if x <= s_w or x > right_limit:
|
||
continue
|
||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||
|
||
if scored:
|
||
scored.sort(key=lambda t: t[0], reverse=True)
|
||
best_val, best_loc = scored[0][1], scored[0][2]
|
||
else:
|
||
best_val, best_loc = candidates[0]
|
||
|
||
distance = best_loc[0] - x_offset
|
||
if distance < 0:
|
||
distance = 0
|
||
if distance + s_w > bg_w:
|
||
distance = bg_w - s_w
|
||
return distance
|
||
|
||
|
||
def generate_track(distance):
|
||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||
aim = distance + overshoot
|
||
steps = []
|
||
moved = 0
|
||
y = 0
|
||
while moved < aim:
|
||
remain = aim - moved
|
||
if remain > 80:
|
||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||
elif remain > 35:
|
||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||
elif remain > 12:
|
||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||
else:
|
||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||
if random.random() < 0.22:
|
||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||
else:
|
||
y = int(round(y * 0.6))
|
||
steps.append((dx, y, dt))
|
||
moved += dx
|
||
if overshoot > 0:
|
||
back = overshoot
|
||
while back > 0:
|
||
dx = -min(back, random.randint(1, 3))
|
||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||
back += dx
|
||
if random.random() < 0.65:
|
||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||
(1, 0, random.uniform(0.020, 0.050)),
|
||
(-1, 0, random.uniform(0.020, 0.050))])
|
||
return steps
|
||
|
||
|
||
def perform_slide(page, btn, distance_css):
|
||
if distance_css <= 0:
|
||
return False
|
||
mid = btn.rect.midpoint
|
||
steps = generate_track(distance_css)
|
||
try:
|
||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||
duration=random.uniform(0.25, 0.60))
|
||
time.sleep(random.uniform(0.18, 0.45))
|
||
page.actions.hold(on_ele=btn)
|
||
time.sleep(random.uniform(0.12, 0.28))
|
||
for dx, dy, dt in steps:
|
||
if dx == 0 and dy == 0:
|
||
time.sleep(dt)
|
||
else:
|
||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||
time.sleep(random.uniform(0.10, 0.26))
|
||
page.actions.release()
|
||
return True
|
||
except Exception as e:
|
||
logger.warning("拖拽异常:%s", e)
|
||
return False
|
||
|
||
|
||
def handle_hr_captcha(page):
|
||
for retry_no in range(HR_RETRY_MAX):
|
||
logger.info("--- HR 第 %d 次尝试验证 ---", retry_no + 1)
|
||
try:
|
||
container = page.ele(CAPTCHA_CONTAINER, timeout=HR_TIMEOUT)
|
||
if not container:
|
||
continue
|
||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||
slider_ele = container.ele(SLIDER_IMG)
|
||
if not bg_ele or not slider_ele:
|
||
continue
|
||
if slider_ele.tag != 'img':
|
||
inner = slider_ele.ele('tag:img')
|
||
if inner:
|
||
slider_ele = inner
|
||
try:
|
||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||
time.sleep(0.2)
|
||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||
time.sleep(0.2)
|
||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||
except Exception:
|
||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||
continue
|
||
|
||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||
distance_css = distance_phys / dpr
|
||
logger.info("匹配距离 %dpx -> CSS %.1fpx", distance_phys, distance_css)
|
||
|
||
btn = page.ele(SLIDER_BTN)
|
||
if btn and perform_slide(page, btn, distance_css):
|
||
time.sleep(2)
|
||
if HR_SUCCESS_KEYWORD in page.url:
|
||
return True
|
||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||
return True
|
||
time.sleep(2)
|
||
except Exception as e:
|
||
logger.warning("验证异常:%s", e)
|
||
time.sleep(1)
|
||
return False
|
||
|
||
|
||
class LoginRequiredError(Exception):
|
||
"""登录态失效:打开页面被重定向到登录页。"""
|
||
|
||
|
||
def _create_page():
|
||
"""创建新的 ChromiumPage(统一配置)。"""
|
||
co = ChromiumOptions()
|
||
if HR_HEADLESS:
|
||
co.headless()
|
||
return ChromiumPage(co)
|
||
|
||
|
||
def hr_login(username=None, password=None):
|
||
load_dotenv()
|
||
final_username = username or os.getenv('hr_login_username')
|
||
final_password = password or os.getenv('hr_login_password')
|
||
if not final_username or not final_password:
|
||
raise RuntimeError("HR 用户名或密码未提供,请设置环境变量 hr_login_username / hr_login_password")
|
||
|
||
page = _create_page()
|
||
|
||
saved = load_cookies(COOKIE_FILE_HR)
|
||
if saved:
|
||
try:
|
||
page.set.cookies(saved)
|
||
page.get(HR_LOGIN_URL)
|
||
time.sleep(2)
|
||
if HR_SUCCESS_KEYWORD in page.url:
|
||
logger.info("已通过缓存的 HR Cookies 登录")
|
||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||
page.quit()
|
||
return
|
||
except Exception as e:
|
||
logger.warning("复用 HR Cookies 失败:%s", e)
|
||
else:
|
||
page.get(HR_LOGIN_URL)
|
||
time.sleep(2)
|
||
|
||
if HR_SUCCESS_KEYWORD in page.url:
|
||
logger.info("HR 已登录")
|
||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||
page.quit()
|
||
return
|
||
|
||
try:
|
||
account = page.ele(ACCOUNT_INPUT_HR)
|
||
if not account:
|
||
raise RuntimeError("找不到 HR 账号输入框")
|
||
account.clear(); account.input(final_username); time.sleep(0.5)
|
||
pwd = page.ele(PASSWORD_INPUT_HR)
|
||
if not pwd:
|
||
raise RuntimeError("找不到 HR 密码输入框")
|
||
pwd.clear(); pwd.input(final_password); time.sleep(0.5)
|
||
login_btn = page.ele(LOGIN_BTN)
|
||
if not login_btn:
|
||
raise RuntimeError("找不到登录按钮")
|
||
login_btn.click(); time.sleep(3)
|
||
|
||
if HR_SUCCESS_KEYWORD in page.url:
|
||
logger.info("HR 登录成功(无滑块)")
|
||
elif handle_hr_captcha(page):
|
||
logger.info("HR 登录成功(验证通过)")
|
||
else:
|
||
raise RuntimeError("HR 登录失败(滑块验证未通过)")
|
||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||
finally:
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# ==================== 花名册导出(浏览器自动化) ====================
|
||
def _click_text(page, text, timeout=10):
|
||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||
if not ele:
|
||
raise RuntimeError(f"未找到元素:{text}")
|
||
ele.click()
|
||
logger.info("已点击:%s", text)
|
||
|
||
|
||
def _click_text_in(page, container, text, timeout=5):
|
||
"""在指定容器内按文本匹配并点击。"""
|
||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||
if not ele:
|
||
raise RuntimeError(f"容器内未找到元素:{text}")
|
||
ele.click()
|
||
logger.info("已点击:%s", text)
|
||
|
||
|
||
def _is_displayed(ele):
|
||
"""判断元素是否可见且具有尺寸(可点击);异常时返回 False(保守不误判)。"""
|
||
if ele is None:
|
||
return False
|
||
try:
|
||
if not ele.states.is_displayed:
|
||
return False
|
||
w, h = ele.rect.size
|
||
return w > 0 and h > 0
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _inject_cookies_and_goto(page, max_retry=3):
|
||
"""注入 HR cookies 并访问花名册页,返回可用的 page。
|
||
|
||
处理两件事:
|
||
1. 断连恢复:登录函数(hr_login)登录后会自行关闭其浏览器;若与原 page 共享
|
||
同一浏览器实例,原 page 连接会断开(报「与页面的连接已断开」)。因此这里
|
||
不依赖旧 page,失败时关闭旧页面、重建新页面、重新注入 cookies 后再访问。
|
||
2. 仍需登录:cookies 不存在或失效时,访问会被重定向到登录页,此时仍会调用
|
||
hr_login() 完成登录,登录后再携带新 cookies 重新打开访问(最多重试 max_retry 次)。
|
||
"""
|
||
for attempt in range(1, max_retry + 1):
|
||
try:
|
||
cookies = load_cookies(COOKIE_FILE_HR)
|
||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||
if cookies:
|
||
page.set.cookies(cookies)
|
||
page.get(ROSTER_URL)
|
||
time.sleep(WAIT_LONG)
|
||
# 登录页特征:存在用户名输入框
|
||
if page.ele('@id=j_username', timeout=2):
|
||
raise LoginRequiredError("HR 登录态已失效")
|
||
logger.info("已进入花名册页面:%s", page.url)
|
||
return page
|
||
except LoginRequiredError:
|
||
logger.info("HR 登录态已失效,执行重新登录")
|
||
hr_login()
|
||
except Exception as e:
|
||
logger.warning("访问花名册页失败(第 %d 次):%s", attempt, e)
|
||
# 关闭旧页面并重建(携带 cookies 重新打开访问)
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
page = _create_page()
|
||
raise RuntimeError(f"登录态/连接恢复失败,连续 {max_retry} 次未能进入花名册页面")
|
||
|
||
|
||
def _select_org_tree(page):
|
||
"""切换到组织树并选中「集团」。"""
|
||
# 步骤1:点击左侧「组织机构」,切换为组织树
|
||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
||
if org_tab:
|
||
org_tab.click()
|
||
logger.info("已点击左侧「组织机构」")
|
||
time.sleep(WAIT_MID)
|
||
else:
|
||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
||
_click_text(page, TAB_ORG)
|
||
time.sleep(WAIT_MID)
|
||
|
||
# 步骤2:点击组织树根节点「集团」
|
||
group = page.ele('css:a[title="集团"]', timeout=15)
|
||
if not group:
|
||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
||
if not group:
|
||
raise RuntimeError("组织树中未找到「集团」节点")
|
||
group.click()
|
||
logger.info("已点击组织树根节点「集团」")
|
||
time.sleep(WAIT_LONG)
|
||
|
||
|
||
def _ensure_person_status(page, status="在职"):
|
||
"""将「在职状态」筛选设置为仅选中指定状态(在职/离职)。
|
||
|
||
注意:该筛选为多选下拉(在职/离职/退休/返聘),需要取消其它已选项,
|
||
仅保留目标状态,避免导出时把多个状态混在一起。
|
||
"""
|
||
container = page.ele('css:div[component-div*="person_status"]', timeout=15)
|
||
if not container:
|
||
raise RuntimeError("未找到「在职状态」筛选控件")
|
||
select = container.ele('css:.el-select', timeout=5)
|
||
if not select:
|
||
raise RuntimeError("未找到「在职状态」下拉框")
|
||
|
||
# 打开下拉,等待可见面板出现(下拉关闭时选项仍在 DOM 但不可见,必须取可见面板内的选项)
|
||
select.click()
|
||
time.sleep(WAIT_SHORT)
|
||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
||
if not panel:
|
||
select.click()
|
||
time.sleep(WAIT_SHORT)
|
||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
||
if not panel:
|
||
raise RuntimeError("在职状态下拉面板未能展开")
|
||
|
||
items = panel.eles('css:li.el-select-dropdown__item')
|
||
if not items:
|
||
raise RuntimeError("在职状态下拉中没有选项")
|
||
|
||
# 文本 -> 选项元素
|
||
opt_map = {}
|
||
for it in items:
|
||
txt = (it.text or "").strip()
|
||
if txt:
|
||
opt_map[txt] = it
|
||
if status not in opt_map:
|
||
raise RuntimeError(f"在职状态下拉中不存在选项:{status}")
|
||
|
||
# 仅保留目标状态选中,其余取消选中
|
||
for txt, it in opt_map.items():
|
||
is_selected = "selected" in (it.attr('class') or "")
|
||
need = (txt == status)
|
||
if is_selected != need:
|
||
logger.info("在职状态选项「%s」%s", txt, "选中" if need else "取消选中")
|
||
it.click()
|
||
time.sleep(0.2)
|
||
|
||
# 关闭下拉(再次点击外壳切换收起)
|
||
try:
|
||
select.click()
|
||
except Exception:
|
||
pass
|
||
time.sleep(WAIT_SHORT)
|
||
logger.info("在职状态已设为仅「%s」", status)
|
||
|
||
|
||
def _open_custom_export_dialog(page):
|
||
"""点击「更多操作」->「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
||
# 若导出弹窗已打开(存在「模板」下拉),直接返回
|
||
tpl_label = page.ele(
|
||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
||
if tpl_label and _is_displayed(tpl_label):
|
||
logger.info("导出弹窗已打开,跳过「更多操作」")
|
||
time.sleep(WAIT_MID)
|
||
return
|
||
|
||
# 步骤3:点击「更多操作」按钮
|
||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=15)
|
||
if more_btn:
|
||
more_btn.click()
|
||
else:
|
||
_click_text(page, BTN_MORE)
|
||
logger.info("已点击「更多操作」")
|
||
time.sleep(WAIT_SHORT)
|
||
|
||
# 步骤4:点击「自定义导出」
|
||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||
if menu:
|
||
_click_text_in(page, menu, MENU_CUSTOM_EXPORT)
|
||
else:
|
||
_click_text(page, MENU_CUSTOM_EXPORT)
|
||
time.sleep(WAIT_MID)
|
||
|
||
|
||
def _select_template(page, template_name):
|
||
"""在导出弹窗中选择自定义导出模板。"""
|
||
# 步骤5:定位「模板」下拉框容器(含「模板」前置标签的 el-select)
|
||
tpl = page.ele(
|
||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
||
'/following-sibling::div[contains(@class,"el-select")]',
|
||
timeout=15,
|
||
)
|
||
if not tpl:
|
||
raise RuntimeError("未找到「模板」下拉框")
|
||
|
||
# 确保下拉面板已展开(下拉面板会 teleport 到 body,需在页面级查找可见面板)
|
||
panel = None
|
||
for _ in range(3):
|
||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
||
if panel and _is_displayed(panel):
|
||
break
|
||
tpl.click()
|
||
time.sleep(WAIT_SHORT)
|
||
if not panel:
|
||
raise RuntimeError("模板下拉面板未能展开")
|
||
|
||
# 步骤6:在可见面板中选择模板(如「雇主险增减员导出模板」)
|
||
opt = panel.ele(
|
||
f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
||
timeout=5,
|
||
)
|
||
if not opt:
|
||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
||
opt.click()
|
||
logger.info("已选择模板:%s", template_name)
|
||
time.sleep(WAIT_SHORT)
|
||
|
||
|
||
def _click_confirm_export(page):
|
||
"""点击「确认导出」,触发下载。"""
|
||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
||
timeout=10)
|
||
if not btn:
|
||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
||
btn.click()
|
||
logger.info("已点击「确认导出」")
|
||
time.sleep(WAIT_SHORT)
|
||
|
||
|
||
def _wait_download(page, download_dir, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||
"""等待下载文件生成并大小稳定,返回下载文件路径。
|
||
|
||
采用文件系统轮询:统计下载目录中新增的、非临时文件,当其大小两次采样一致
|
||
视为下载完成。避免依赖 DrissionPage 下载任务状态(可能卡在 100% 不结束)。
|
||
"""
|
||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||
before = set(os.listdir(download_dir))
|
||
deadline = time.time() + timeout
|
||
last_sizes = {}
|
||
while time.time() < deadline:
|
||
try:
|
||
files = os.listdir(download_dir)
|
||
except Exception:
|
||
files = []
|
||
for f in files:
|
||
if f in before or f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
||
continue
|
||
p = os.path.join(download_dir, f)
|
||
if not os.path.isfile(p):
|
||
continue
|
||
try:
|
||
size = os.path.getsize(p)
|
||
except Exception:
|
||
continue
|
||
if size <= 0:
|
||
continue
|
||
if last_sizes.get(p) == size:
|
||
logger.info("花名册导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
||
return p
|
||
last_sizes[p] = size
|
||
time.sleep(1.0)
|
||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
||
|
||
|
||
# ==================== 统一格式合并(与 app 版 roster_export._merge_roster_files 一致) ====================
|
||
def _normalize_and_save(files_with_status, output_path):
|
||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||
|
||
统一输出格式(后续筛选复制按此规范读取):
|
||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||
- 「类型」列统一追加在最后一列,标识在职状态
|
||
- 单 sheet,表头在第1行,数据第2行起
|
||
|
||
Args:
|
||
files_with_status: [(status, file_path), ...] 列表
|
||
output_path: 合并后文件保存路径
|
||
|
||
Returns:
|
||
合并后文件路径
|
||
"""
|
||
dfs = []
|
||
for status, path in files_with_status:
|
||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||
df["类型"] = status # 类型列统一追加到最后一列
|
||
dfs.append(df)
|
||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||
merged = pd.concat(dfs, ignore_index=True)
|
||
|
||
_ensure_dir(os.path.dirname(output_path))
|
||
merged.to_excel(output_path, index=False)
|
||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||
|
||
# 删除临时下载的单个文件
|
||
for _, path in files_with_status:
|
||
try:
|
||
os.remove(path)
|
||
except Exception:
|
||
pass
|
||
return output_path
|
||
|
||
|
||
# ==================== 导出入口 ====================
|
||
@retry(max_attempts=3)
|
||
def _export_one_status(page, status, download_dir, template_name):
|
||
"""导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||
logger.info(">>> 开始导出在职状态:%s(模板:%s)", status, template_name)
|
||
try:
|
||
_ensure_person_status(page, status)
|
||
_open_custom_export_dialog(page)
|
||
_select_template(page, template_name)
|
||
_click_confirm_export(page)
|
||
logger.info(">>> 等待在职状态「%s」的导出文件下载", status)
|
||
path = _wait_download(page, download_dir)
|
||
logger.info(">>> 在职状态「%s」导出完成", status)
|
||
return path
|
||
except Exception:
|
||
logger.exception("导出在职状态「%s」失败,详细堆栈如下:", status)
|
||
raise
|
||
|
||
|
||
def export_roster(download_dir=None, template_name=None, output_path=None, statuses=None):
|
||
"""执行雇主险花名册自定义导出,按统一格式保存为源表。
|
||
|
||
Args:
|
||
download_dir: 浏览器下载临时目录,默认 D:\\资料\\人资\\员工花名册
|
||
template_name: 自定义导出模板名,默认「雇主险增减员导出模板」
|
||
output_path: 合并后文件的保存路径,默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx
|
||
statuses: 需要导出的在职状态列表,默认仅 ["在职"](雇主险增减员只需在职人员)
|
||
|
||
Returns:
|
||
合并后的花名册文件路径。
|
||
|
||
Raises:
|
||
RuntimeError: 任何流程步骤失败或下载未检测到时抛出。
|
||
"""
|
||
download_dir = os.path.abspath(download_dir or DEFAULT_DOWNLOAD_DIR)
|
||
template_name = template_name or DEFAULT_TEMPLATE
|
||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||
output_path = os.path.abspath(output_path or DEFAULT_OUTPUT_PATH)
|
||
_ensure_dir(download_dir)
|
||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s),下载目录:%s =====",
|
||
template_name, statuses, download_dir)
|
||
|
||
page = _create_page()
|
||
logger.info("浏览器已启动")
|
||
try:
|
||
# 注入缓存 cookies 并进入花名册页
|
||
# (连接断开自动重建页面;cookies 失效则重新登录后再访问,见 _inject_cookies_and_goto)
|
||
page = _inject_cookies_and_goto(page)
|
||
_select_org_tree(page)
|
||
|
||
# 下载目录设置需在触发下载前完成
|
||
page.set.download_path(download_dir)
|
||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||
|
||
files_with_status = []
|
||
for status in statuses:
|
||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||
path = _export_one_status(page, status, download_dir, template_name)
|
||
files_with_status.append((status, path))
|
||
time.sleep(WAIT_MID)
|
||
|
||
# 合并所有花名册文件,输出统一格式源表
|
||
result = _normalize_and_save(files_with_status, output_path)
|
||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||
return result
|
||
finally:
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# ==================== 主入口 ====================
|
||
def main():
|
||
load_dotenv()
|
||
try:
|
||
out = export_roster(
|
||
download_dir=os.getenv("roster_download_dir"),
|
||
template_name=os.getenv("roster_template"),
|
||
output_path=os.getenv("roster_output_path"),
|
||
statuses=[s.strip() for s in os.getenv("roster_statuses", "").split(",") if s.strip()] or None,
|
||
)
|
||
logger.info("===== 花名册导出完成:%s =====", out)
|
||
except Exception as e:
|
||
logger.error("花名册导出失败:%s", e)
|
||
raise
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|