Files
37duAutomation/app/service/hrbp/oa/common/parser.py
T

154 lines
4.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@Module: hrbp.oa.parser
@FileName: parser.py
@Author: 小布丁
@CreateTime: 2026-08-05 17:10
@Description: 解析模块(处理 SSO 302 跳转、HTML 排班表格解析)
@Version: 1.0.0
"""
from DrissionPage import SessionPage
from urllib.parse import urlparse, parse_qs
import re
from typing import Dict, List
# ---------- SSO 跳转解析 ----------
def extract_real_url_and_params(session: SessionPage, sso_url: str) -> Dict[str, str]:
"""
访问 SSO 链接,从 302 重定向的 Location 头中提取真实详情页 URL,
并解析出 taskId 和 businessKey。
Args:
session: 已登录的 SessionPage 对象
sso_url: SSO 跳转链接(完整 URL)
Returns:
包含 taskId 和 businessKey 的字典
Raises:
RuntimeError: 非 30x 状态码、无 Location 头或参数缺失
"""
print(f"🔗 解析 SSO: {sso_url}")
# 禁止自动重定向,仅获取响应头
session.get(sso_url, allow_redirects=False)
resp = session.response
if resp.status_code not in (301, 302, 303, 307, 308):
raise RuntimeError(f"SSO 链接未返回重定向状态码,实际: {resp.status_code}")
location = resp.headers.get("Location")
if not location:
raise RuntimeError("重定向响应中未找到 Location 头")
# 补全为绝对 URL(若为相对路径)
if not location.startswith(("http://", "https://")):
if location.startswith("/"):
parsed = urlparse(sso_url)
base = f"{parsed.scheme}://{parsed.netloc}"
location = base + location
else:
raise RuntimeError(f"无法解析相对路径 Location: {location}")
print(f"📍 真实详情页 URL: {location}")
# 解析查询参数
parsed = urlparse(location)
params = parse_qs(parsed.query)
task_id = params.get("taskId", [None])[0]
business_key = params.get("businessKey", [None])[0]
if not task_id or not business_key:
raise RuntimeError(f"详情页 URL 缺少 taskId 或 businessKey: {location}")
return {"taskId": task_id, "businessKey": business_key}
# ---------- 排班 HTML 解析 ----------
def parse_attendance_html(html: str) -> Dict[str, str]:
"""
解析排班 HTML 表格,提取每个日期的班次名称。
示例 HTML 片段:
<a class='cale_a' ... data-temp='2026-08-01' ...>正常</a>
或 <a ...>休息</a>
Args:
html: 排班接口返回的 HTML 字符串
Returns:
字典:{日期字符串: 班次名称}
例如:{"2026-08-01": "正常", "2026-08-02": "休息"}
"""
# 正则匹配 <a> 标签中的 data-temp 和文本内容
pattern = r'<a[^>]*data-temp="([^"]+)"[^>]*>([^<]+)</a>'
matches = re.findall(pattern, html)
result = {}
for date, shift in matches:
# 去除可能的空格
date_clean = date.strip()
shift_clean = shift.strip()
result[date_clean] = shift_clean
return result
def get_work_days_in_range(
attendance_dict: Dict[str, str],
start_date: str,
end_date: str
) -> List[str]:
"""
根据排班字典和请假起止日期,返回请假区间内所有非“休息”的日期列表。
Args:
attendance_dict: 由 parse_attendance_html 返回的字典
start_date: 请假开始日期,格式 "YYYY-MM-DD"
end_date: 请假结束日期,格式 "YYYY-MM-DD"
Returns:
非休息日的日期字符串列表(格式 "YYYY-MM-DD")
"""
from datetime import datetime, timedelta
start = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
work_days = []
current = start
while current <= end:
date_str = current.strftime("%Y-%m-%d")
shift = attendance_dict.get(date_str, "")
# 如果该日期没有排班信息,或明确为“休息”,视为休息日
if shift != "休息" and shift != "":
work_days.append(date_str)
current += timedelta(days=1)
return work_days
# ---------- 使用示例(测试用) ----------
if __name__ == "__main__":
# 测试 SSO 解析(需要有效的 session)
# from hrbp.oa.login import oa_login
# from hrbp.oa.session_manager import init_session_from_page
# browser = oa_login()
# session = init_session_from_page(browser)
# sso_url = "https://oa.37du.co/sso/..." # 替换为实际链接
# params = extract_real_url_and_params(session, sso_url)
# print(params)
# 测试 HTML 解析
sample_html = """
<a class='cale_a' data-temp="2026-08-01">休息</a>
<a class='cale_a' data-temp="2026-08-02">正常</a>
<a class='cale_a' data-temp="2026-08-03">休息</a>
"""
result = parse_attendance_html(sample_html)
print(result) # {'2026-08-01': '休息', '2026-08-02': '正常', '2026-08-03': '休息'}
work = get_work_days_in_range(result, "2026-08-01", "2026-08-03")
print(work) # ['2026-08-02']