# -*- coding: utf-8 -*- """ @Module: hrbp.ehr.common @FileName: login.py @Author: 小布丁 @CreateTime: 2026-08-05 23:52 @Description: HR 登录 + 滑块验证(改进版:双候选 + 低置信度容忍) @Version: 1.1.0 """ import os import re import json import time import random from PIL import Image, ImageDraw from DrissionPage import ChromiumPage, ChromiumOptions import cv2 import numpy as np import io from dotenv import load_dotenv load_dotenv() # ================== 配置 ================== LOGIN_URL = os.getenv('hr_login_url') SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword') USERNAME = os.getenv('hr_login_username') PASSWORD = os.getenv('hr_login_password') LOGIN_BTN = "@id=login-btn" ACCOUNT_INPUT = "@id=j_username" PASSWORD_INPUT = "@id=j_password_2" CAPTCHA_CONTAINER = ".:comImageValidate" SLIDER_BTN = ".:v_rightBtn" BG_IMG = ".imgBg" SLIDER_IMG = "css:div.imgBg_3 > img" # 注意:不再使用 REFRESH_BTN RETRY_MAX = 5 TIMEOUT = 10 HEADLESS = False DEBUG_DIR = os.path.join(os.path.dirname(__file__), 'captcha_debug') # 登录 cookies 持久化目录(与 OA 系统一致,服务层统一管理各平台会话文件) _COOKIE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions') COOKIE_FILE = os.path.join(_COOKIE_DIR, 'hr_cookies.json') def ensure_dir(path): os.makedirs(path, exist_ok=True) # ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ================== def save_browser_cookies(page): """把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。""" cookies = page.cookies(all_domains=True) if not cookies: print("未获取到 Cookies,跳过保存") return ensure_dir(_COOKIE_DIR) with open(COOKIE_FILE, 'w', encoding='utf-8') as f: json.dump(cookies, f, ensure_ascii=False, indent=2) print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}") def load_cookies(): """从本地文件加载 cookies 列表;文件不存在或为空时返回 None。""" if not os.path.exists(COOKIE_FILE): return None with open(COOKIE_FILE, encoding='utf-8') as f: cookies = json.load(f) return cookies or None # ================== 改进的匹配函数(双候选 + 低置信度容忍) ================== def match_slider_dual(bg_bytes, slider_bytes, debug_prefix=""): """ 双候选匹配,返回最佳候选和次佳候选(即使置信度低) 返回: (best_distance, best_conf, best_loc, candidates_list, x_offset, y_offset, slider_w, slider_h) 其中 candidates_list 为 [(x, y, conf), ...] 用于绘制标记 """ 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: print(f" [{debug_prefix}匹配错误] 无法解码图片") return None, 0, None, [], 0, 0, 0, 0 bg_h, bg_w = bg_img.shape[:2] s_h, s_w = slider_color.shape[:2] print(f" [{debug_prefix}图片尺寸] 背景: {bg_w}x{bg_h}, 滑块原始: {s_w}x{s_h}") # ---- 提取滑块有效区域 ---- x_offset = 0 y_offset = 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 and len(xs) > 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 = x_min y_offset = y_min print(f" [{debug_prefix}滑块裁剪] 有效区域: x=[{x_min},{x_max}], y=[{y_min},{y_max}], 裁剪后尺寸: {slider_rgb.shape[1]}x{slider_rgb.shape[0]}") else: print(f" [{debug_prefix}滑块裁剪] 未找到非透明区域,使用完整图") slider_rgb = slider_color[:, :, :3] else: if len(slider_color.shape) == 3: slider_rgb = slider_color else: slider_rgb = cv2.cvtColor(slider_color, cv2.COLOR_GRAY2BGR) x_offset = 0 y_offset = 0 s_h, s_w = slider_rgb.shape[:2] # ---- 预处理:灰度 + 高斯模糊 + Canny ---- gray_bg = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY) gray_slider = cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY) gray_bg = cv2.GaussianBlur(gray_bg, (3, 3), 0) gray_slider = cv2.GaussianBlur(gray_slider, (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) # 收集多个候选(前 6 个),避免真实缺口被最右侧干扰或滑块区假候选挤掉 candidates = [] temp_result = result.copy() for i 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: print(f" [{debug_prefix}] 无有效候选") return None, 0, None, [], x_offset, y_offset, s_w, s_h # 最右侧判定为干扰项:真实缺口不会紧贴背景图最右端 right_margin = max(15, int(bg_w * 0.06)) right_limit = bg_w - s_w - right_margin # 真实缺口常为半透明白色矩形,白度是强判别信号(区域近白像素占比) 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()) # 在有效区间 [s_w, right_limit] 内按「置信度 + 白度」综合评分选择 scored = [] for val, loc in candidates: x, y = loc if x <= s_w or x > right_limit: # 排除左端滑块区与最右侧干扰 continue wn = region_whiteness(x, y, s_w, s_h) score = val + 0.5 * wn scored.append((score, val, loc)) print(f" [{debug_prefix}] 有效候选 loc={loc} conf={val:.4f} 白度={wn:.2f} 综合={score:.4f}") if not scored: best_val, best_loc = candidates[0] # 全部落在无效区,回退全局最高 print(f" [{debug_prefix}] 无有效区候选,回退最高置信度: loc={best_loc}, val={best_val:.4f}") else: scored.sort(key=lambda t: t[0], reverse=True) best_val, best_loc = scored[0][1], scored[0][2] print(f" [{debug_prefix}] 选择综合最优候选: loc={best_loc}, conf={best_val:.4f}") distance_phys = best_loc[0] - x_offset if distance_phys < 0: distance_phys = 0 if distance_phys + s_w > bg_w: distance_phys = bg_w - s_w # ---- 若置信度极低,尝试 ORB 辅助 ---- if best_val < 0.25 and len(candidates) > 0: orb = cv2.ORB_create(nfeatures=500) kp1, des1 = orb.detectAndCompute(slider_edges, None) kp2, des2 = orb.detectAndCompute(bg_edges, None) if des1 is not None and des2 is not None and len(kp1) > 5 and len(kp2) > 5: bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches = bf.match(des1, des2) matches = sorted(matches, key=lambda x: x.distance) if len(matches) > 10: good = [m for m in matches[:30] if m.distance < np.mean([m.distance for m in matches[:15]]) * 0.7] if len(good) > 5: src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2) offsets = dst_pts - src_pts median_offset = np.median(offsets, axis=0)[0] orb_x = int(median_offset[0]) - x_offset if 0 < orb_x < bg_w - s_w: print(f" [{debug_prefix}] ORB辅助偏移: {orb_x}px (原模板置信度{best_val:.3f})") distance_phys = orb_x best_val = 0.5 # 提升置信度用于显示 # ---- 构建候选列表(用于绘图) ---- candidate_points = [] for val, loc in candidates: candidate_points.append((loc[0], loc[1], val)) print(f" [{debug_prefix}最终物理距离] distance={distance_phys}px (置信度 {best_val:.4f})") return distance_phys, best_val, best_loc, candidate_points, x_offset, y_offset, s_w, s_h def draw_match_debug_multi(bg_bytes, slider_bytes, candidate_points, best_loc, x_offset, y_offset, slider_w, slider_h, distance_phys, distance_css, save_path): """在背景图上绘制所有候选矩形和最佳匹配""" try: bg_img = Image.open(io.BytesIO(bg_bytes)).convert("RGBA") draw = ImageDraw.Draw(bg_img) # 绘制所有候选(灰色虚线框) for i, (cx, cy, conf) in enumerate(candidate_points): if (cx, cy) == (best_loc[0], best_loc[1]): continue # 最佳单独绘制 rect = [cx, cy, cx + slider_w, cy + slider_h] draw.rectangle(rect, outline="gray", width=1) draw.text((cx + 5, cy - 10), f"conf={conf:.2f}", fill="gray") # 绘制最佳匹配(红色实线) if best_loc: rect = [best_loc[0], best_loc[1], best_loc[0] + slider_w, best_loc[1] + slider_h] draw.rectangle(rect, outline="red", width=3) text = f"best phys={distance_phys} css={distance_css}" draw.text((best_loc[0] + 5, best_loc[1] - 20), text, fill="red") bg_img.save(save_path) print(f" [匹配标记] 已保存: {save_path}") except Exception as e: print(f" [匹配标记] 绘制失败: {e}") # ================== 轨迹生成与滑动(与原相同) ================== 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)) dt = random.uniform(0.030, 0.080) if random.random() < 0.35: y = random.choice([-1, 0, 1]) steps.append((dx, y, dt)) 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) if random.random() < 0.08: time.sleep(random.uniform(0.010, 0.035)) time.sleep(random.uniform(0.10, 0.26)) page.actions.release() return True except Exception as e: print(f"拖拽异常:{e}") return False # ================== 验证码处理(移除刷新按钮,容忍低置信度) ================== def handle_captcha(page): ensure_dir(DEBUG_DIR) dpr = page.run_js('return window.devicePixelRatio') print(f"设备像素比(DPR): {dpr}") for retry in range(RETRY_MAX): print(f"\n--- 第 {retry+1} 次尝试验证 ---") try: container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT) if not container: print("验证码容器未出现") continue bg_ele = container.ele(BG_IMG) if not bg_ele: bg_ele = container.ele('div[style*="background-image"]') if not bg_ele: print("找不到背景图元素") continue slider_ele = container.ele(SLIDER_IMG) if not slider_ele: print("找不到滑块小图元素") continue if slider_ele.tag != 'img': img_inner = slider_ele.ele('tag:img') if img_inner: slider_ele = img_inner # 隐藏滑块 -> 截取背景 -> 恢复 -> 截取滑块 bg_screenshot = None slider_screenshot = None 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 as e: print(f"隐藏/截图过程出错:{e}") try: page.run_js('arguments[0].style.display = ""', slider_ele) except: pass continue if not bg_screenshot or not slider_screenshot: print("截图数据为空") continue # 保存原始截图 bg_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}.png") slider_path = os.path.join(DEBUG_DIR, f"slider_{retry}.png") with open(bg_path, 'wb') as f: f.write(bg_screenshot) with open(slider_path, 'wb') as f: f.write(slider_screenshot) print(f" [调试截图] 背景: {bg_path}") print(f" [调试截图] 滑块: {slider_path}") # 调用改进的匹配函数 ret = match_slider_dual(bg_screenshot, slider_screenshot, debug_prefix=f"retry{retry}") if ret[0] is None: print("匹配失败,无候选,尝试随机拖动触发刷新") # 随机拖动一段距离(比如100-300px)尝试触发刷新 random_css = random.uniform(100, 300) / dpr btn = page.ele(SLIDER_BTN) if btn: perform_slide(page, btn, random_css) time.sleep(2) continue distance_phys, conf, best_loc, candidate_points, x_offset, y_offset, slider_w, slider_h = ret # 转换为 CSS 距离 distance_css = distance_phys / dpr print(f" [置信度] {conf:.4f},物理距离: {distance_phys}px,CSS距离: {distance_css:.1f}px") # 生成标记图(绘制所有候选) marked_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}_marked.png") draw_match_debug_multi(bg_screenshot, slider_screenshot, candidate_points, best_loc, x_offset, y_offset, slider_w, slider_h, distance_phys, distance_css, marked_path) if distance_css <= 0: print(" CSS距离无效,尝试随机拖动") random_css = random.uniform(100, 300) / dpr btn = page.ele(SLIDER_BTN) if btn: perform_slide(page, btn, random_css) time.sleep(2) continue btn = page.ele(SLIDER_BTN) if not btn: print("找不到滑块按钮") continue # 执行滑动 perform_slide(page, btn, distance_css) time.sleep(2) # 等待验证结果 # 检查是否登录成功 if SUCCESS_KEYWORD in page.url: return True # 若验证码容器消失,则认为验证通过 if not page.ele(CAPTCHA_CONTAINER, timeout=1): return True else: print("验证未通过,等待自动刷新...") # 不点击刷新按钮,等待网站自行更新验证码 time.sleep(2) except Exception as e: print(f"异常:{e}") time.sleep(1) return False # ================== 登录主流程(不变) ================== def login(): co = ChromiumOptions() if HEADLESS: co.headless() page = ChromiumPage(co) # 尝试复用已保存的 cookies,免重复登录 saved = load_cookies() if saved: try: page.set.cookies(saved) page.get(LOGIN_URL) time.sleep(2) if SUCCESS_KEYWORD in page.url: print("已通过缓存的 Cookies 登录") return True print("缓存的 Cookies 已失效,重新登录") except Exception as e: print(f"复用 Cookies 失败:{e}") else: page.get(LOGIN_URL) time.sleep(2) if SUCCESS_KEYWORD in page.url: print("已登录") return True account = page.ele(ACCOUNT_INPUT) if not account: print("找不到账号输入框") return False account.clear() account.input(USERNAME) time.sleep(0.5) pwd = page.ele(PASSWORD_INPUT) if not pwd: print("找不到密码输入框") return False pwd.clear() pwd.input(PASSWORD) time.sleep(0.5) login_btn = page.ele(LOGIN_BTN) if not login_btn: print("找不到登录按钮") return False login_btn.click() time.sleep(3) if SUCCESS_KEYWORD in page.url: print("登录成功(无滑块)") save_browser_cookies(page) return True if handle_captcha(page): print("登录成功(验证通过)") save_browser_cookies(page) return True else: print("登录失败") return False if __name__ == "__main__": success = login() print("最终结果:", "成功" if success else "失败")