import time import json import random import re import os import uuid from datetime import datetime from typing import List, Dict, Optional, Any, Callable from DrissionPage import ChromiumPage from plugin import IPlugin from core_types import ( PluginConfig, AppointmentType, QueryResult, BookResult, AvailabilityStatus, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str ) from utils.cloudflare_bypass_for_scraping import CloudflareBypasser from utils.mouse import HumanMouse from utils.keyboard import HumanKeyboard from utils.flow_engine import BaseFlow, on, guard, done, fatal from utils.plugin_utils import ( init_chromium_options, filter_dates_in_range, cleanup_browser_workspace, save_screenshot ) class UsaLoginFlow(BaseFlow): """ 基于 BaseFlow 注解状态机驱动的美签 USVisaScheduling 会话创建与自动导航流 """ def __init__(self, page, plugin: 'UsaPlugin', interval: float = 1.0): super().__init__( page=page, config=plugin.config, context={"plugin": plugin}, interval=interval, logger=plugin._log, cf_bypasser=CloudflareBypasser(page, log=True, logger=plugin._log), max_stuck_cycles=30 ) self.plugin = plugin self.login_submit_attempts = 0 self.last_login_submit_time = 0.0 # --- 异常守卫与自愈 (Priority 5~7) --- @guard(text="502 Bad Gateway", priority=5) @guard(text="503 Service Temporarily Unavailable", priority=5) def on_server_network_error(self): self.log("[WARN] 检测到服务器网络错误 (502/503),等待并刷新自愈...", level="warning") self.plugin._random_sleep(30, 40) self.page.refresh() try: self.page.wait.doc_loaded() except Exception: pass @guard(text="Sorry, you have been blocked", priority=6) @guard(text="You are being rate limited", priority=6) @guard(text="Cloudflare Ray ID", priority=6) @fatal("Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.") def on_cloudflare_blocked(self): pass @guard(title="just a moment", priority=7) @guard(title="请稍候", priority=7) @guard(predicate=lambda flow: flow.cf_bypasser and not flow.cf_bypasser.is_bypassed(), priority=7) def on_cloudflare_5s_challenge(self): self.log("🛡️ 检测到 Cloudflare 5秒盾,正在尝试穿透...") if self.cf_bypasser.bypass(max_retry=8): self.log("✅ Cloudflare 挑战通过!") self.plugin._random_sleep(2, 4) self.cf_bypasser.handle_waiting_room() else: self.log("[WARN] 本周期未完全通过 Cloudflare,将在下一周期继续尝试...") @guard(title="waitting room", priority=7) @guard(title="waiting room", priority=7) def on_cloudflare_waiting_room(self): self.log("🛡️ 检测到 Cloudflare 等候室,正在等待自动排队刷新...") self.cf_bypasser.handle_waiting_room() time.sleep(2) # --- 状态流转与表单处理 (Priority 35~50) --- @on(ele="#signInName", priority=50) def handle_login_form(self): # 1. 冷却保护:若距离上次提交不足 15 秒,避免高频点击,静候跳转 if time.time() - self.last_login_submit_time < 15.0: self.log("Login form recently submitted, waiting for redirect...") time.sleep(2) return # 2. 检查是否有页面报错(如凭证无效、被锁等) err_ele = ( self.page.ele('.pageLevel', timeout=0.2) or self.page.ele('.claimVerificationServerError', timeout=0.2) or self.page.ele('.error:not([aria-hidden="true"])', timeout=0.2) ) if err_ele and err_ele.text: err_msg = err_ele.text.strip().replace('\n', ' ') self.log(f"[WARN] 登录页面提示错误: '{err_msg}'", level="warning") if any(k in err_msg.lower() for k in ["invalid", "无效", "locked", "锁定"]): if self.login_submit_attempts >= 2: raise BizLogicError(f"美签登录凭据无效或账号被锁定: {err_msg}") # 3. 最大重试上限防护 if self.login_submit_attempts >= 5: raise BizLogicError("登录失败:已重试 5 次登录仍停留在登录页面,请检查账号密码或代理网络。") self.login_submit_attempts += 1 self.log(f"[State] Login page detected. Submitting credentials (attempt {self.login_submit_attempts}/5)...") username = self.plugin.config.account.username password = self.plugin.config.account.password username_input = self.page.ele('#signInName') self.plugin.mouse.human_click_ele(username_input) username_input.clear() self.plugin.keyboard.type_text(username, humanize=True) self.plugin._random_sleep(2, 4) password_input = self.page.ele('#password') self.plugin.mouse.human_click_ele(password_input) password_input.clear() self.plugin.keyboard.type_text(password, humanize=True) self.plugin._random_sleep(2, 4) continue_btn = self.page.ele('#continue') if continue_btn: self.plugin.mouse.human_click_ele(continue_btn) self.last_login_submit_time = time.time() self.log("Login form submitted. Waiting for the next step to load...") self.plugin._random_sleep(10, 15) def _extract_security_answer(self, security: Any, q_num: str) -> Optional[str]: if not security: return None # 1. 列表格式: ["ans1", "ans2", "ans3"] if isinstance(security, list): idx = int(q_num) - 1 if 0 <= idx < len(security): return str(security[idx]) return None # 2. 字典格式 if isinstance(security, dict): # 极简键格式: {"1": "ans1", "2": "ans2"} 或 {1: "ans1", 2: "ans2"} if q_num in security: val = security[q_num] return str(val.get('a', '')) if isinstance(val, dict) else str(val) if q_num.isdigit() and int(q_num) in security: val = security[int(q_num)] return str(val.get('a', '')) if isinstance(val, dict) else str(val) # 旧版嵌套键格式: {"1_quest": {"a": "ans1"}} 或 {"1_quest": "ans1"} config_key = f"{q_num}_quest" if config_key in security: val = security[config_key] return str(val.get('a', '')) if isinstance(val, dict) else str(val) return None @on(ele="xpath://input[starts-with(@id, 'kba') and contains(@id, '_response')]", priority=45) def handle_kba_security_questions(self): self.log("[State] Security question verification detected. Filling in answers...") security = self.plugin.free_config.get('security') answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]') if not security: save_screenshot(self.page, self.plugin.instance_id, "kba_security_missing", logger=self.log) err_msg = "美签登录触发了 KBA 密保问题验证,但在 free_config 中未配置 'security' 答案,无法继续登录。" self.log(f"[ERROR] {err_msg}", level="error") raise BizLogicError(err_msg) for ans_ele in answer_eles: ele_id = ans_ele.attr('id') match = re.search(r'kba(\d+)_response', ele_id) if match: q_num = match.group(1) ans_text = self._extract_security_answer(security, q_num) if ans_text is None: save_screenshot(self.page, self.plugin.instance_id, f"kba_q{q_num}_missing", logger=self.log) err_msg = f"美签登录触发了第 {q_num} 道密保问题,但配置中未提供对应答案(当前配置: {security})。" self.log(f"[ERROR] {err_msg}", level="error") raise BizLogicError(err_msg) self.plugin.mouse.human_click_ele(ans_ele) ans_ele.clear() self.plugin.keyboard.type_text(ans_text, humanize=True) self.log(f"-> Found input {ele_id}, successfully filled in answer for question {q_num}.") continue_btn = self.page.ele('#continue') if continue_btn: self.plugin.mouse.human_click_ele(continue_btn) self.log("Security answers submitted. Waiting for redirection...") self.plugin._random_sleep(30, 40) @on(ele="#atlas-sidebar", priority=35) def handle_dashboard_sidebar(self): self.log("[State] At the main booking dashboard. Looking for navigation button...") # 1. 优先检查重新安排预约按钮 (#reschedule_appointment,针对已有预约账号的改约) reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5) if reschedule_btn: self.log("Currently in rescheduling mode ('#reschedule_appointment'), clicking to proceed...") self.plugin.mouse.human_click_ele(reschedule_btn) self.plugin._random_sleep(15, 25) return # 2. 检查首次预约按钮 (#schedule_appointment) schedule_btn = self.page.ele('#schedule_appointment', timeout=0.5) if schedule_btn: self.log("Currently in first-time booking mode ('#schedule_appointment'), clicking to proceed...") self.plugin.mouse.human_click_ele(schedule_btn) self.plugin._random_sleep(15, 25) return # 3. 检查动态注入的 admin_link 安排预约 admin_link = self.page.ele('#admin_link', timeout=0.5) if admin_link: self.log("Found '#admin_link' (安排预约), clicking to proceed...") self.plugin.mouse.human_click_ele(admin_link) self.plugin._random_sleep(15, 25) return # 4. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本匹配预约/改约的链接 fallback_link = ( self.page.ele('css:#atlas-sidebar a[href*="schedule"]', timeout=0.5) or self.page.ele('xpath://*[@id="atlas-sidebar"]//a[contains(text(), "安排预约") or contains(text(), "重新安排预约") or contains(text(), "Schedule") or contains(text(), "Reschedule")]', timeout=0.5) ) if fallback_link: self.log(f"Found sidebar booking link (text='{fallback_link.text}'), clicking to proceed...") self.plugin.mouse.human_click_ele(fallback_link) self.plugin._random_sleep(15, 25) return self.log("Not found schedule or reschedule button. The page may still be loading...") time.sleep(2) # --- 成功终态到达 (Priority 10) --- @on(ele="#post_select", priority=10) @done def on_reached_slot_search_page(self): self.plugin.session_create_time = time.time() self.log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!") class UsaPlugin(IPlugin): name = "usa_plugin" version = "1.0.0" description = "美签USVisaScheduling预约插件 (B2C认证、流控调度与自动占位)" LOCATIONS = { "BEIJING": {"name": "BEIJING", "id": "106bf614-b0db-ec11-a7b4-001dd80234f6"}, "GUANGZHOU": {"name": "GUANGZHOU", "id": "a26af614-b0db-ec11-a7b4-001dd80234f6"}, "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"}, "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"}, "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"}, } def __init__(self, group_id: str): self.group_id = group_id self.config: Optional[PluginConfig] = None self.free_config: Dict[str, Any] = {} self.is_healthy = True self.logger = None self.mouse = None self.keyboard = None self.page: Optional[ChromiumPage] = None self.instance_id = uuid.uuid4().hex[:8] self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}")) self.user_data_path = os.path.join(self.root_workspace, "user_data") if not os.path.exists(self.root_workspace): os.makedirs(self.root_workspace) self.tunnel = None self.session_create_time: float = 0 def _log(self, message): if self.logger: self.logger(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}') else: print(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}') def _random_sleep(self, min_sec=30, max_sec=60): """ 核心防限速控制:模拟人类阅读和操作的长时间停顿,确保网络请求间隔在30-60秒 """ sleep_time = random.uniform(min_sec, max_sec) self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...") time.sleep(sleep_time) def set_config(self, config: PluginConfig): """设置 API 的配置信息""" self.config = config self.free_config = config.free_config or {} def set_log(self, logger: Callable[[str], None]) -> None: """设置日志输出工具""" self.logger = logger def keep_alive(self): """ 通过页面内原生轻量 fetch 请求进行保活(每10秒调用一次): 1. 保持底层 HTTP/2 和代理长连接活跃,防止连接中断或代理切换 IP 2. 维持 Cloudflare 会话与 Session 活跃状态 3. 轻量请求 /favicon.ico,不增加后端业务负担 """ if not self.page or not self.is_healthy: return try: # 在浏览器页面上下文内发起轻量 fetch 请求 (/favicon.ico) js_code = """ return fetch('/favicon.ico?_t=' + Date.now(), { method: 'GET', cache: 'no-store', credentials: 'include' }).then(r => ({ status: r.status, ok: r.ok })) .catch(e => ({ status: 0, error: e.message })); """ result = self.page.run_js(js_code) status = result.get("status", 0) if isinstance(result, dict) else 0 self._log(f"🟡 [KeepAlive] Ping 响应状态: {status}") except Exception as e: self._log(f"⚠️ [KeepAlive] 保活调用异常: {e}") def health_check(self) -> bool: if not self.is_healthy: return False if self.page is None: return False try: if not self.page.run_js("return 1;"): return False except Exception: return False if self.config.session_max_life > 0: current_time = time.time() elapsed_time = current_time - self.session_create_time if elapsed_time > self.config.session_max_life: self._log("Session expired.") return False return True def _bypass_cf_via_new_tab(self) -> bool: """ 打开新标签页访问首页,绕过 Cloudflare 机器人验证页面并获取更新的 clearance 凭据, 完成后关闭新标签页并切换回原排期页面。 """ root_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/" self._log(f"Opening new tab to '{root_url}' to bypass Cloudflare verification...") tab = None original_tab_id = self.page.tab_id try: # 1. 打开新标签页 tab = self.page.new_tab(root_url) self._random_sleep(2, 3) # 2. 检查并穿透 Cloudflare 机器人验证 / 5秒盾 cf_bypasser = CloudflareBypasser(tab, log=True, logger=self._log) page_title = (getattr(tab, "title", "") or "").lower() if not cf_bypasser.is_bypassed() or any(w in page_title for w in ["just a moment", "请稍候", "attention required", "cloudflare"]): self._log("🛡️ 检测到新标签页触发 Cloudflare 挑战,正在穿透...") if not cf_bypasser.bypass(max_retry=8): self._log("[WARN] 新标签页 Cloudflare 穿透未完全成功") self._random_sleep(2, 4) cf_bypasser.handle_waiting_room() else: self._log("新标签页未触发挑战或已通过 Cloudflare 验证。") self._random_sleep(1, 2) cf_bypasser.handle_waiting_room() self._log("✅ 新标签页 Cloudflare 验证处理完成。") return True except Exception as e: self._log(f"[ERROR] 新标签页穿透 Cloudflare 发生异常: {e}") return False finally: if tab: try: tab.close() self._log("新标签页已关闭。") except Exception as e: self._log(f"[WARN] 关闭新标签页失败: {e}") try: self.page.activate_tab(original_tab_id) except Exception as e: self._log(f"[DEBUG] 激活原排期标签页失败: {e}") self._random_sleep(1, 2) def create_session(self) -> None: """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)""" self._log(f"Initializing Session (ID: {self.instance_id})...") self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id if self.config and self.config.proxy else 'None'}") co, self.tunnel = init_chromium_options( user_data_path=self.user_data_path, username_seed=self.config.account.username if self.config and self.config.account else None, proxy=self.config.proxy if self.config else None, headless=False, window_size="1920,1080", logger=self._log ) self.page = ChromiumPage(co) self._log("Init humanize tools...") self.mouse = HumanMouse(self.page, debug=False) self.keyboard = HumanKeyboard(self.page) viewport_width = self.page.rect.viewport_size[0] viewport_height = self.page.rect.viewport_size[1] init_x = random.randint(10, viewport_width - 10) init_y = random.randint(10, viewport_height - 10) self.mouse.move(init_x, init_y) usa_url = self.free_config.get('usa_url', '') if usa_url: self._log(f"Navigating: {usa_url}") self.page.get(usa_url) # 启动 UsaLoginFlow 注解流状态机 login_flow = UsaLoginFlow( self.page, plugin=self, interval=1.0 ) login_flow.run(max_steps=100, timeout=600.0) self.session_create_time = time.time() self._log("🎉 UsaLoginFlow completed successfully. Session created.") def query(self, apt_type: AppointmentType) -> QueryResult: """查询可用的签证预约信息""" self._log("Querying available slots...") res = QueryResult() res.success = False location_name = (self.free_config.get('location') or "").strip() # 最多尝试 3 次:首次查询 + 若遇 PSE0501/CF质询/超时则在新标签页过盾重试 for attempt in range(3): current_url = (getattr(self.page, "url", "") or "").lower() if "schedule" not in current_url: self._log(f"Current url '{current_url}' not on schedule page, navigating...") schedule_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/zh-CN/schedule/" self.page.get(schedule_url) self._random_sleep(3, 5) else: self._log("Already on schedule page, waiting for dynamic elements to finish loading...") if "just a moment" in (getattr(self.page, "title", "") or "").lower(): cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else False, logger=self._log) if not cf_bypasser.bypass(max_retry=5): raise BizLogicError("Cloudflare bypass timeout") self._random_sleep(3, 5) cf_bypasser.handle_waiting_room() current_url = (getattr(self.page, "url", "") or "").lower() if 'auth' in current_url or 'login' in current_url: self.is_healthy = False raise SessionExpiredOrInvalidError() # 1. 等待申请人列表加载(从 page1 空列表异步加载到 page2) self._log("Waiting for applicant list (#gm_select) to populate...") self.page.ele("css:#gm_select label", timeout=30) # 2. 等待领事馆下拉框选项加载完成 self._log("Waiting for consular post options to populate in #post_select...") post_select = self.page.ele('#post_select', timeout=30) if not post_select: if attempt < 2: self._log("[WARN] 未找到 #post_select,尝试在新标签页绕过人机验证重试...") self._bypass_cf_via_new_tab() continue raise BizLogicError("Element #post_select not found.") # 等待至少出现一个有效选项 self.page.ele("css:#post_select option:not([value=''])", timeout=30) # 获取所有已加载的领事馆 options all_options = post_select.eles("tag:option") available_options = [opt for opt in all_options if (getattr(opt, "attrs", {}).get("value") or "").strip()] opts_summary = [f"{opt.text} ({getattr(opt, 'attrs', {}).get('value')})" for opt in available_options] self._log(f"Available consular posts: {opts_summary}") # 3. 匹配目标领事馆 matched_id = None # 策略 A: 优先检查 LOCATIONS 字典 known_info = self.LOCATIONS.get(location_name.upper()) if known_info: target_id = known_info["id"] if any(opt.attrs.get("value") == target_id for opt in available_options): matched_id = target_id # 策略 B: 按文本包含匹配(例如 "GUANGZHOU" 或 "广州") if not matched_id: for opt in available_options: opt_text = (getattr(opt, "text", "") or "").upper() if location_name.upper() in opt_text: matched_id = opt.attrs.get("value") break # 策略 C: 针对当前申请锁定特定城市(如账号当前仅有广州选项)自适应兜底 if not matched_id and available_options: fallback_opt = available_options[0] matched_id = fallback_opt.attrs.get("value") self._log(f"[WARN] Configured location '{location_name}' not available. Auto-selecting active consular post: '{fallback_opt.text}' ({matched_id})") if not matched_id: raise BizLogicError(f"No matching consular post found for location '{location_name}'. Available: {[opt.text for opt in available_options]}") # 开启监听目标 API target_api = 'get-family-consular-schedule-days' self.page.listen.start(target_api) # 4. 选择领事馆并触发 change 事件 (此操作会触发上述 API 的 AJAX 请求) self._log(f"Selecting consular post ID: {matched_id}...") post_select.select.by_value(matched_id) try: self.page.run_js('$("#post_select").val(arguments[0]).trigger("change");', matched_id) except Exception as e: self._log(f"[DEBUG] Triggering change event via JS: {e}") # 5. 等待拦截 API 响应 (设置超时时间) self._log("Waiting for schedule dates API response...") packet = None try: packet = self.page.listen.wait(timeout=20) finally: self.page.listen.stop() # 仅在未收到响应或状态码非 200 时检查是否有错误弹窗(如 PSE0501) if not packet or packet.response.status != 200: alert_msg = None try: alert_msg = self.page.handle_alert(accept=True, timeout=0.2) except Exception: pass if alert_msg: self._log(f"[WARN] 页面弹出提示: '{alert_msg}'") is_pse0501 = bool(alert_msg and ("PSE0501" in alert_msg or "无法加载可预约日期" in alert_msg)) # 场景 1: 遇到 PSE0501 或 403 (CF 质询拦截) if is_pse0501 or (packet and packet.response.status == 403): if attempt < 2: self._log("[WARN] 检测到 PSE0501 或 HTTP 403 质询,通过新标签页访问首页绕过人机验证...") self._bypass_cf_via_new_tab() continue if alert_msg: raise BizLogicError(f"页面弹出提示: {alert_msg}") err_msg = str(packet.response.body)[:256] if packet else "Forbidden" raise PermissionDeniedError(f"HTTP 403: {err_msg}") # 场景 2: 未收到响应数据包 (超时) if not packet: if attempt < 2: self._log("[WARN] 未收到排期响应数据包,尝试通过新标签页绕过人机验证重试...") self._bypass_cf_via_new_tab() continue if alert_msg: raise BizLogicError(f"页面弹出提示: {alert_msg}") raise BizLogicError("Timeout waiting for schedule API response") # 场景 3: 其他 HTTP 异常状态码 (如 429) status_code = packet.response.status body = packet.response.body if isinstance(body, bytes): body = body.decode("utf-8", errors="ignore") err_text = str(body)[:512] if status_code == 429: self.is_healthy = False raise RateLimiteddError(f"HTTP 429: {err_text}") raise BizLogicError(f"HTTP {status_code} error. resp={err_text}") status_code = packet.response.status body = packet.response.body if isinstance(body, bytes): body = body.decode("utf-8", errors="ignore") self._log(f"API Response Status: {status_code}") # 6. 解析返回的数据 available_dates = [] data = body if isinstance(body, dict) else None if not data: match = re.search(r'(\{.*\})', str(body), re.DOTALL) data = json.loads(match.group(1)) if match else json.loads(str(body)) schedule_days = data.get("ScheduleDays", []) if schedule_days: for day_obj in schedule_days: date_str = day_obj.get("Date") if date_str: available_dates.append(date_str) # 6. 处理最终结果 if available_dates: available_dates.sort() res.success = True res.availability_status = AvailabilityStatus.Available earliest_date = available_dates[0] res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d") res.availability = [ DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[]) for d in available_dates ] self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}") else: res.success = False res.availability_status = AvailabilityStatus.NoneAvailable self._log("No slots available.") return res def book(self, slot_info: QueryResult, user_inputs) -> BookResult: """进行预约操作""" res = BookResult() res.success = False exp_start = user_inputs.get('expected_date_start', '') exp_end = user_inputs.get('expected_date_end', '') available_dates_str = [ da.date.strftime("%Y-%m-%d") for da in slot_info.availability if da.date ] valid_dates_list = filter_dates_in_range(available_dates_str, exp_start, exp_end, shuffle=True) if not valid_dates_list: raise NotFoundError(message="No dates match user constraints") selected_slot_date = random.choice(valid_dates_list) book_date_obj = datetime.strptime(selected_slot_date, "%Y-%m-%d").date() # jQuery UI Datepicker 月份是 0-11 target_day = str(book_date_obj.day) target_month = str(book_date_obj.month - 1) target_year = str(book_date_obj.year) self._log(f"Target booking date: {selected_slot_date}. Navigating calendar...") # 1. 适配不在当前日历的情况:通过下拉框选择年份和月份 year_select = self.page.ele('.ui-datepicker-year', timeout=10) # 查找年份下拉框 if year_select and year_select.value != target_year: self._log(f"Changing year to {target_year}") year_select.select.by_value(target_year) self._random_sleep(0.5, 1) month_select = self.page.ele('.ui-datepicker-month', timeout=10) # 查找月份下拉框 if month_select and month_select.value != target_month: self._log(f"Changing month to {target_month}") month_select.select.by_value(target_month) self._random_sleep(0.5, 1) # 2. 点击目标日期 self._log(f"Clicking date {selected_slot_date}...") target_cell_selector = f"xpath://td[@data-year='{target_year}' and @data-month='{target_month}']//a[text()='{target_day}']" target_date_cell = self.page.ele(target_cell_selector, timeout=10) if not target_date_cell: raise BizLogicError(f"Target date element not found for {selected_slot_date} after navigating.") self.mouse.human_click_ele(target_date_cell) self._log("Waiting for available times to load...") self._random_sleep(3, 5) # 3. 等待并选择时间 self._log("Selecting earliest available time...") slot_time_selector = "css:#time_select input[name='schedule-entries']" first_time_radio = self.page.ele(slot_time_selector, timeout=15) if not first_time_radio: raise BizLogicError("Failed to load time slots after clicking date. Might be rate limited or slots gone.") selected_slot_time = first_time_radio.parent().text.strip() self.mouse.human_click_ele(first_time_radio) # 4. 点击提交 self._random_sleep(1, 2) self._log("Submitting booking...") submit_appointment_selector = "#submitbtn" submit_button = self.page.ele(submit_appointment_selector, timeout=10) self.mouse.human_click_ele(submit_button) # A click is not a receipt. Require the site's confirmation page and # visible appointment details; a timeout must be reconciled. confirmed = False for _ in range(30): current_url = str(self.page.url).lower() if ('appointment-confirmation' in current_url or 'appointment_confirmation' in current_url): details = self.page.ele('tag:body', timeout=0.5) if details and selected_slot_date in str(details.text): confirmed = True break error = self.page.ele('css:.validation-summary-errors', timeout=0.2) if error and str(error.text).strip(): return res time.sleep(0.5) if not confirmed: raise BizLogicError('USA submission has no verified appointment confirmation') # 构造返回结果 res = BookResult() res.success = True res.book_date = selected_slot_date res.book_time = selected_slot_time res.account = self.config.account.username res.label = current_url return res def cleanup(self): """销毁浏览器并彻底删除临时文件""" if getattr(self, "keep_browser_on_error", False): self._log("[DEBUG] keep_browser_on_error 生效,跳过浏览器清理并保留窗口供分析。") return cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log) self.page = None self.tunnel = None def get_plugin_status(self) -> PluginStatus: account_name = self.config.account.username if self.config and self.config.account else "" proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else "" current_url = "" if self.page: try: current_url = self.page.url except Exception: pass session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0 state = "running" if self.is_healthy else "unhealthy" return PluginStatus( instance_id=self.instance_id, is_healthy=self.is_healthy, state=state, current_url=current_url, account=account_name, proxy=proxy_info, session_age_sec=session_age, last_active_at=utc_now_str(), ) def __del__(self): """ 析构函数:当对象被垃圾回收时自动调用 """ self.cleanup()