# -*- coding: utf-8 -*- """ @Module: hrbp.ehr.wage_card @FileName: roster_export.py @Author: 小布丁 @CreateTime: 2026-08-08 @Description: 员工花名册自定义导出。复用 HR 系统登录及缓存 cookies,通过 DrissionPage 浏览器自动化 按 aa.md 流程操作:进入花名册页 -> 组织机构(集团) -> 在职状态=在职 -> 更多操作 -> 自定义导出 -> 选择模板「员工基础信息」-> 确认导出,并接收浏览器下载的文件到指定目录。 @Version: 1.0.0 使用说明: 1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json; 后续运行自动复用缓存,登录态过期会自动重新登录。 2. 直接运行本文件即可触发花名册导出(会弹出浏览器窗口,请勿关闭)。 3. 下载目录默认取环境变量 roster_output_dir,否则使用项目根目录。 底层复用: - HR 登录 & cookies:app.service.hrbp.common.login(load_cookies / login) - 页面地址 & 模板名:app.service.hrbp.ehr.common.config(ROSTER_URL / ROSTER_TEMPLATE_NAME) """ import os import sys import time from pathlib import Path # ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ---- def _find_project_root() -> str: for parent in Path(__file__).resolve().parents: if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file(): return str(parent) return str(Path(__file__).resolve().parents[5]) _root = _find_project_root() if _root not in sys.path: sys.path.insert(0, _root) from app.utils.logger import get_logger # noqa: E402 from app.utils.logger import setup_logging # noqa: E402 try: from DrissionPage import ChromiumPage, ChromiumOptions except ImportError: ChromiumPage = None ChromiumOptions = None try: import pandas as pd except ImportError: pd = None # 底层复用:HR 登录 / cookies / 配置 / 重试 / 离职时间范围 from app.service.hrbp.ehr.common.config import ROSTER_URL, ROSTER_TEMPLATE_NAME # noqa: E402 from app.service.hrbp.common.login import load_cookies # noqa: E402 from app.service.hrbp.ehr.wage_card.wage_card_download import get_leave_range # noqa: E402 from app.utils.intelligent_retry import retry # noqa: E402 logger = get_logger(__name__) # ===================== 流程步骤所用文案常量(aa.md 提供) ===================== TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树 TREE_GROUP = "集团" # 组织树根节点 PERSON_STATUSES = ["在职", "离职"] # 需导出的在职状态(按顺序逐次导出) BTN_MORE = "更多操作" # 更多操作按钮 MENU_CUSTOM_EXPORT = "自定义导出" TEMPLATE_PLACEHOLDER = "请选择模板" BTN_CONFIRM = "确认导出" BTN_MORE_SEARCH = "更多搜索" # 展开更多筛选条件(离职时间等) LEAVE_RANGE_PLACEHOLDER = "请选择离职时间" 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_BEGIN_TIMEOUT = 60 # 等待下载开始 DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成 # 输出目录 & 合并文件名 OUTPUT_DIR = r"D:\资料\人资\员工花名册" MERGED_NAME = "员工花名册.xlsx" # --------------------------------------------------------------- # 1. 元素定位辅助(DrissionPage) # --------------------------------------------------------------- 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 _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 _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 _open_more_search(page): """确保「更多搜索」popover 已展开,返回是否成功。 通过按钮的 aria-describedby 属性找到 popover 内容元素,检查其是否可见来判断展开状态。 按钮特征:class 含 search-more-condition-btn / el-popover__reference,外层容器 demo-search-more。 """ # 定位「更多搜索」按钮 btn = page.ele('css:button.search-more-condition-btn', timeout=3) if not btn: btn = page.ele('css:.demo-search-more .el-popover__reference', timeout=2) if not btn: btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2) if not btn: logger.warning("未找到「更多搜索」按钮") return False for _ in range(3): # 通过 aria-describedby 找到 popover 元素,检查是否可见 popover_id = btn.attr('aria-describedby') if popover_id: popover = page.ele(f'css:#{popover_id}', timeout=2) if popover and _is_displayed(popover): logger.info("更多搜索已展开(popover #%s 可见)", popover_id) return True # 兜底:检查是否有可见的「筛选」按钮 fb = page.ele(FILTER_XPATH, timeout=2) if fb and _is_displayed(fb): logger.info("更多搜索已展开(检测到可见的「筛选」按钮)") return True # 用 JS 直接 click() 触发 Element UI popover(纯选择器,避免传参问题) page.run_js( 'var b=document.querySelector("button.search-more-condition-btn");' 'if(b){b.click();}' ) time.sleep(WAIT_MID) logger.warning("「更多搜索」未能展开") return False def _click_filter(page): """点击更多搜索弹层底部的「筛选」按钮,应用离职时间等筛选条件。 全部在 JS 中完成:定位 popover -> 在 popover 内部找文本为「筛选」的按钮 -> 直接 .click()。 之前全页面搜索可能找到错误的「筛选」按钮,现在限定在 popover 容器内查找。 """ result = page.run_js( 'var b=document.querySelector("button.search-more-condition-btn");' 'if(!b){return "no_btn_more";}' 'var id=b.getAttribute("aria-describedby");' 'if(!id){return "no_id";}' 'var pop=document.getElementById(id);' 'if(!pop){return "no_popover:"+id;}' 'var btns=pop.querySelectorAll("button");' 'for(var i=0;i「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。""" # 若导出弹窗已打开(存在「模板」下拉),直接返回 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=ROSTER_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) # --------------------------------------------------------------- # 4. 下载等待 # --------------------------------------------------------------- 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 内未检测到稳定文件)") # --------------------------------------------------------------- # 5. 合并多个花名册 Excel 为一个,添加「类型」列 # --------------------------------------------------------------- def _merge_roster_files(files_with_status, output_path): """合并多个花名册 Excel 文件,添加「类型」列标识在职状态。 统一输出格式(各业务场景读取端按此规范读取): - 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题) - 「类型」列统一追加在最后一列,标识在职状态(在职/离职) - 单 sheet,表头在第1行,数据第2行起 Args: files_with_status: [(status, file_path), ...] 列表 output_path: 合并后文件保存路径 Returns: 合并后文件路径 """ if pd is None: raise RuntimeError("缺少 pandas 依赖,无法合并 Excel") 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) 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 # --------------------------------------------------------------- # 6. 对外入口 # --------------------------------------------------------------- @retry(max_attempts=3) def _export_one_status(page, status, download_dir, template_name): """导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。 Args: template_name: 自定义导出模板名(如「员工基础信息」「雇主险增减员导出模板」)。 """ logger.info(">>> 开始导出在职状态:%s(模板:%s)", status, template_name) try: _ensure_person_status(page, status) if status == "离职": _set_leave_date_range(page) _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: str = None, template_name: str = ROSTER_TEMPLATE_NAME, output_path: str = None, statuses: list = None) -> str: """执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。 Args: download_dir: 浏览器下载临时目录,默认使用 OUTPUT_DIR。 template_name: 自定义导出模板名,可按业务场景动态传入(默认「员工基础信息」)。 output_path: 合并后文件的保存路径,由调用方传入(如某业务目录下的花名册文件); 默认使用 OUTPUT_DIR/员工花名册.xlsx。 statuses: 需要导出的在职状态列表,默认 ["在职", "离职"]; 业务场景可按需传入(如雇主险只需在职时传 ["在职"])。 Returns: 合并后的花名册文件路径。 Raises: RuntimeError: 任何流程步骤失败或下载未检测到时抛出。 """ if ChromiumPage is None: raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage") statuses = list(statuses) if statuses else list(PERSON_STATUSES) download_dir = os.path.abspath(download_dir or OUTPUT_DIR) os.makedirs(download_dir, exist_ok=True) logger.info("===== 开始花名册导出(模板:%s,在职状态:%s),下载目录:%s =====", template_name, statuses, download_dir) co = ChromiumOptions() page = ChromiumPage(co) logger.info("浏览器已启动") try: # 注入缓存 cookies,再访问页面 cookies = load_cookies() logger.info("加载缓存 cookies:%d 个", len(cookies or [])) if cookies: try: page.set.cookies(cookies) except Exception as e: logger.warning("注入缓存 cookies 失败:%s", e) _ensure_logged_in(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) # 合并所有花名册文件 merged_path = os.path.abspath(output_path or os.path.join(OUTPUT_DIR, MERGED_NAME)) os.makedirs(os.path.dirname(merged_path), exist_ok=True) result = _merge_roster_files(files_with_status, merged_path) logger.info("===== 花名册导出并合并完成:%s =====", result) return result finally: try: page.quit() except Exception: pass def debug_filter_only(): """调试模式:只执行到筛选结束,不导出,浏览器保持打开供检查。""" if ChromiumPage is None: raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage") logger.info("===== 调试模式:仅执行到筛选结束 =====") co = ChromiumOptions() page = ChromiumPage(co) logger.info("浏览器已启动") try: cookies = load_cookies() logger.info("加载缓存 cookies:%d 个", len(cookies or [])) if cookies: try: page.set.cookies(cookies) except Exception as e: logger.warning("注入缓存 cookies 失败:%s", e) _ensure_logged_in(page) _select_org_tree(page) _ensure_person_status(page, "离职") _set_leave_date_range(page) logger.info("===== 筛选已执行完毕,浏览器保持打开,按回车关闭 =====") input("按回车键关闭浏览器...") except Exception as e: logger.error("调试失败:%s", e) raise finally: try: page.quit() except Exception: pass def main() -> None: """命令行入口:python roster_export.py [下载目录] [模板名] 模板名也可通过环境变量 roster_template 传入,优先级:命令行参数 > 环境变量 > 默认「员工基础信息」。 """ setup_logging() # 调试模式:仅执行到筛选结束 if len(sys.argv) > 1 and sys.argv[1] == "debug": debug_filter_only() return download_dir = os.getenv("roster_output_dir") if not download_dir and len(sys.argv) > 1 and sys.argv[1] != "debug": download_dir = sys.argv[1] template_name = os.getenv("roster_template") if not template_name and len(sys.argv) > 2: template_name = sys.argv[2] template_name = template_name or ROSTER_TEMPLATE_NAME try: out = export_roster(download_dir, template_name) logger.info("===== 花名册导出完成:%s =====", out) except Exception as e: logger.error("花名册导出失败:%s", e) raise if __name__ == "__main__": main()