usa_plugin.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. import time
  2. import json
  3. import random
  4. import re
  5. import os
  6. import uuid
  7. import shutil
  8. import socket
  9. from datetime import date, datetime
  10. from typing import List, Dict, Optional, Any, Callable
  11. from urllib.parse import urljoin, urlparse, urlencode, parse_qs
  12. from concurrent.futures import ThreadPoolExecutor
  13. from DrissionPage import ChromiumPage, ChromiumOptions
  14. import configure
  15. from vs_plg import IVSPlg
  16. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  17. from toolkit.mihomo_tunnel import MihomoTunnel
  18. from utils.mouse import HumanMouse
  19. from utils.keyboard import HumanKeyboard
  20. from utils.fingerprint_utils import FingerprintGenerator
  21. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  22. class BrowserResponse:
  23. """模拟 requests.Response"""
  24. def __init__(self, result_dict):
  25. result_dict = result_dict or {}
  26. self.status_code = result_dict.get('status', 0)
  27. self.text = result_dict.get('body', '')
  28. self.headers = result_dict.get('headers', {})
  29. self.url = result_dict.get('url', '')
  30. self._json = None
  31. def json(self):
  32. if self._json is None:
  33. if not self.text:
  34. return {}
  35. try:
  36. self._json = json.loads(self.text)
  37. except:
  38. self._json = {}
  39. return self._json
  40. class UsaPlugin(IVSPlg):
  41. LOCATIONS = {
  42. "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"},
  43. "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"},
  44. "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"},
  45. }
  46. def __init__(self, group_id: str):
  47. self.group_id = group_id
  48. self.config: Optional[VSPlgConfig] = None
  49. self.free_config: Dict[str, Any] = {}
  50. self.is_healthy = True
  51. self.logger = None
  52. self.mouse = None
  53. self.keyboard = None
  54. self.page: Optional[ChromiumPage] = None
  55. self.instance_id = uuid.uuid4().hex[:8]
  56. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  57. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  58. if not os.path.exists(self.root_workspace):
  59. os.makedirs(self.root_workspace)
  60. self.tunnel = None
  61. self.session_create_time: float = 0
  62. def _log(self, message):
  63. if self.logger:
  64. self.logger(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  65. else:
  66. print(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  67. def _random_sleep(self, min_sec=30, max_sec=60):
  68. """
  69. 核心防限速控制:模拟人类阅读和操作的长时间停顿,确保网络请求间隔在30-60秒
  70. """
  71. sleep_time = random.uniform(min_sec, max_sec)
  72. self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...")
  73. time.sleep(sleep_time)
  74. def _get_free_port(self):
  75. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  76. s.bind(('', 0))
  77. return s.getsockname()[1]
  78. def set_config(self, config: VSPlgConfig):
  79. """设置 API 的配置信息"""
  80. self.config = config
  81. self.free_config = config.free_config or {}
  82. def set_log(self, logger: Callable[[str], None]) -> None:
  83. """设置日志输出工具"""
  84. self.logger = logger
  85. def keep_alive(self):
  86. pass
  87. def health_check(self) -> bool:
  88. if not self.is_healthy:
  89. return False
  90. if self.page is None:
  91. return False
  92. try:
  93. if not self.page.run_js("return 1;"):
  94. return False
  95. except:
  96. return False
  97. if self.config.session_max_life > 0:
  98. current_time = time.time()
  99. elapsed_time = current_time - self.session_create_time
  100. if elapsed_time > self.config.session_max_life:
  101. self._log(f"Session expired.")
  102. return False
  103. return True
  104. def _save_screenshot(self, name_prefix):
  105. try:
  106. timestamp = int(time.time())
  107. filename = f"{self.instance_id}_{name_prefix}_{timestamp}.jpg"
  108. save_path = os.path.join("data", filename)
  109. os.makedirs("data", exist_ok=True)
  110. self.page.get_screenshot(path=save_path, full_page=False)
  111. self._log(f"Screenshot saved to {save_path}")
  112. except Exception as e:
  113. self._log(f"Failed to save screenshot: {e}")
  114. def create_session(self) -> None:
  115. """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
  116. self._log(f"Initializing Session (ID: {self.instance_id})...")
  117. def get_free_port():
  118. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  119. s.bind(('', 0))
  120. return s.getsockname()[1]
  121. co = ChromiumOptions()
  122. debug_port = get_free_port()
  123. self._log(f"Assigned Debug Port: {debug_port}")
  124. self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
  125. co.set_local_port(debug_port)
  126. co.set_user_data_path(self.user_data_path)
  127. chrome_path = configure.CHROME_PATH
  128. if not chrome_path:
  129. chrome_path = os.getenv("CHROME_BIN")
  130. if chrome_path and os.path.exists(chrome_path):
  131. co.set_paths(browser_path=chrome_path)
  132. if self.config.proxy and self.config.proxy.ip:
  133. p = self.config.proxy
  134. if p.username and p.password:
  135. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  136. exit_node = {
  137. "name": "ExitNode",
  138. "type": p.proto,
  139. "server": p.ip,
  140. "port": p.port,
  141. "username": p.username,
  142. "password": p.password
  143. }
  144. relay_node = None
  145. if configure.MIHOMO_RELAY_NODES:
  146. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  147. mihomo_path = configure.MIHOMO_BIN_PATH
  148. if not mihomo_path:
  149. mihomo_path = os.getenv("MIHOMO_BIN")
  150. if not mihomo_path:
  151. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  152. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  153. local_proxy = self.tunnel.start()
  154. self._log(f"Tunnel started at {local_proxy}")
  155. co.set_argument(f'--proxy-server={local_proxy}')
  156. else:
  157. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  158. co.set_argument(f'--proxy-server={proxy_str}')
  159. else:
  160. self._log("[WARN] No proxy configured!")
  161. specific_fp = FingerprintGenerator().generate(self.config.account.username)
  162. fp_seed = specific_fp.get("seed")
  163. fp_platform = specific_fp.get("platform")
  164. fp_brand = specific_fp.get("brand")
  165. self._log(f'browser fingerprint seed={fp_seed}')
  166. co.headless(False)
  167. co.set_argument('--no-sandbox')
  168. co.set_argument('--disable-dev-shm-usage')
  169. co.set_argument('--window-size=1920,1080')
  170. co.set_argument('--disable-blink-features=AutomationControlled')
  171. co.set_argument(f"--fingerprint={fp_seed}")
  172. co.set_argument(f"--fingerprint-platform={fp_platform}")
  173. co.set_argument(f"--fingerprint-brand={fp_brand}")
  174. self.page = ChromiumPage(co)
  175. # 获取基础 URL
  176. usa_url = self.free_config.get('usa_url', '')
  177. self._log(f"Navigating: {usa_url}")
  178. self.page.get(usa_url)
  179. self._random_sleep(3, 5)
  180. if 'Attention Required! | Cloudflare' in self.page.title and 'Sorry, you have been blocked' in self.page.html:
  181. self._log(f'Block by cloudflare, try refresh...')
  182. self.page.refresh()
  183. self.page.wait.doc_loaded()
  184. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  185. if not cf_bypasser.bypass(max_retry=6):
  186. raise BizLogicError("Cloudflare bypass timeout")
  187. self._random_sleep(3, 5)
  188. cf_bypasser.handle_waiting_room()
  189. self._log("Init humanize tools...")
  190. self.mouse = HumanMouse(self.page, debug=False)
  191. self.keyboard = HumanKeyboard(self.page)
  192. viewport_width = self.page.rect.viewport_size[0]
  193. viewport_height = self.page.rect.viewport_size[1]
  194. init_x = random.randint(10, viewport_width - 10)
  195. init_y = random.randint(10, viewport_height - 10)
  196. self.mouse.move(init_x, init_y)
  197. username = self.config.account.username
  198. password = self.config.account.password
  199. security = self.free_config.get('security', {})
  200. max_steps = 15 # 由于状态多,步数可以稍微调大一点
  201. stuck_counter = 0
  202. last_url = ""
  203. session_created = False
  204. has_submitted_login = False
  205. for step in range(max_steps):
  206. self.page.wait.doc_loaded()
  207. time.sleep(1) # 这个用于等待页面DOM渲染,保留短时,因为不是发请求
  208. current_url = self.page.url
  209. current_title = self.page.title.lower()
  210. current_html_content = self.page.html
  211. self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
  212. # --- [异常处理层] ---
  213. if current_url == last_url:
  214. stuck_counter += 1
  215. else:
  216. last_url = current_url
  217. stuck_counter = 0
  218. if stuck_counter >= 3:
  219. self._log("[WARN] Page stucked, try to refresh...")
  220. self.page.refresh()
  221. self._random_sleep(30, 40)
  222. stuck_counter = 0
  223. continue
  224. # 网络出现故障,直接重试
  225. server_error_indicators = ["502 Bad Gateway", "503 Service Temporarily Unavailable"]
  226. if any(err in current_html_content for err in server_error_indicators):
  227. self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
  228. self.page.refresh()
  229. self._random_sleep(30, 40)
  230. continue
  231. cloudflare_blocked_indicators = [
  232. "Sorry, you have been blocked" in current_html_content,
  233. "You are being rate limited" in current_html_content,
  234. "Cloudflare Ray ID" in current_html_content
  235. ]
  236. if any(cloudflare_blocked_indicators):
  237. raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  238. # 遇到五秒盾先绕盾
  239. if "just a moment" in current_title:
  240. if not cf_bypasser.bypass(max_retry=3):
  241. continue
  242. self._random_sleep(3, 5)
  243. cf_bypasser.handle_waiting_room()
  244. continue
  245. if self.page.ele('#post_select', timeout=1):
  246. self._log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!")
  247. self.session_create_time = time.time()
  248. session_created = True
  249. break
  250. # 状态 2: 密保问题页面
  251. elif self.page.ele('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]', timeout=1):
  252. self._log("[State] Security question verification detected. Filling in answers...")
  253. answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]')
  254. for ans_ele in answer_eles:
  255. ele_id = ans_ele.attr('id')
  256. match = re.search(r'kba(\d+)_response', ele_id)
  257. if match:
  258. q_num = match.group(1)
  259. config_key = f"{q_num}_quest"
  260. q_data = security.get(config_key)
  261. ans_text = q_data.get('a')
  262. self.mouse.human_click_ele(ans_ele)
  263. self.keyboard.type_text(ans_text, humanize=True)
  264. self._log(f"-> Find input {ele_id}, successfully filled in the answer for question {q_num}.")
  265. continue_btn = self.page.ele('#continue')
  266. self.mouse.human_click_ele(continue_btn)
  267. self._log("Security answers submitted. Waiting for redirection...")
  268. self._random_sleep(30, 40)
  269. continue
  270. # 状态 1: 登录页面
  271. elif self.page.ele('#signInName', timeout=1):
  272. self._log("[State] Login page detected. Submitting credentials...")
  273. username_selector = '#signInName'
  274. username_input = self.page.ele(username_selector)
  275. self.mouse.human_click_ele(username_input)
  276. username_input.clear()
  277. self.keyboard.type_text(username, humanize=True)
  278. self._random_sleep(3, 5)
  279. password_selector = '#password'
  280. password_input = self.page.ele(password_selector)
  281. self.mouse.human_click_ele(password_input)
  282. password_input.clear()
  283. self.keyboard.type_text(password, humanize=True)
  284. self._random_sleep(3, 5)
  285. continue_btn_selector = '#continue'
  286. continue_btn = self.page.ele(continue_btn_selector)
  287. self.mouse.human_click_ele(continue_btn)
  288. has_submitted_login = True
  289. self._log("Login form submitted. Waiting for the next step to load...")
  290. self._random_sleep(30, 40)
  291. continue
  292. elif self.page.ele('#continue_application', timeout=1):
  293. schedule_btn = self.page.ele('#continue_application', timeout=0.5)
  294. self._log("Currently in first-time booking mode, clicking to proceed...")
  295. self.mouse.human_click_ele(schedule_btn)
  296. self._random_sleep(30, 40)
  297. # 状态 3: 预约主页(控制台) -> 选择首签或改签
  298. elif self.page.ele('#atlas-sidebar', timeout=1):
  299. self._log("[State] At the main booking dashboard. Looking for navigation button...")
  300. reschedule_btn_selector = '#reschedule_appointment'
  301. schedule_btn_selector = '#schedule_appointment'
  302. reschedule_btn = self.page.ele(reschedule_btn_selector, timeout=0.5)
  303. if reschedule_btn:
  304. self._log("Currently in rescheduling mode, clicking to proceed...")
  305. self.mouse.human_click_ele(reschedule_btn)
  306. self._random_sleep(30, 40)
  307. else:
  308. schedule_btn = self.page.ele(schedule_btn_selector, timeout=0.5)
  309. if schedule_btn:
  310. self._log("Currently in first-time booking mode, clicking to proceed...")
  311. self.mouse.human_click_ele(schedule_btn)
  312. self._random_sleep(30, 40)
  313. else:
  314. self._log("Not found schedule or reschedule button. The page may still be loading...")
  315. time.sleep(2)
  316. continue
  317. else:
  318. self._log("[State] In unknown or transitional state. Waiting for next polling cycle...")
  319. time.sleep(2)
  320. if not session_created:
  321. raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
  322. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  323. """查询可用的签证预约信息"""
  324. self._log("Querying available slots...")
  325. res = VSQueryResult()
  326. res.success = False
  327. self.page.refresh()
  328. if "just a moment" in self.page.title:
  329. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  330. if not cf_bypasser.bypass(max_retry=5):
  331. raise BizLogicError("Cloudflare bypass timeout")
  332. self._random_sleep(3, 5)
  333. cf_bypasser.handle_waiting_room()
  334. current_url = self.page.url.lower()
  335. if 'auth' in current_url or 'login' in current_url:
  336. self.is_healthy = False
  337. raise SessionExpiredOrInvalidError()
  338. applicant = self.free_config.get('applicant')
  339. location_name = self.free_config.get('location')
  340. location_id = self.LOCATIONS.get(location_name.upper(), {}).get('id')
  341. # 2. 等待页面元素
  342. self.page.ele(f"xpath://label[text()='{applicant}']", timeout=60)
  343. post_select = self.page.ele('#post_select', timeout=60)
  344. # ==================== 新增:网络监听逻辑 ====================
  345. # 开启监听目标 API
  346. target_api = 'get-family-consular-schedule-days'
  347. self.page.listen.start(target_api)
  348. # 3. 选择领事馆 (此操作会触发上述 API 的 AJAX 请求)
  349. self.page.ele(f"xpath://select[@id='post_select']/option[@value='{location_id}']", timeout=60)
  350. post_select.select.by_value(location_id)
  351. # 4. 等待拦截 API 响应 (设置超时时间)
  352. self._log("Waiting for schedule dates API response...")
  353. packet = self.page.listen.wait(timeout=30)
  354. self.page.listen.stop()
  355. if not packet:
  356. raise BizLogicError("Timeout waiting for schedule API response")
  357. status_code = packet.response.status
  358. raw_resp = packet.response.raw_body
  359. self._log(f"API Response Status: {status_code}")
  360. # 处理 HTTP 返回码不是200的情况
  361. if status_code != 200:
  362. if status_code == 403:
  363. raise PermissionDeniedError(f"HTTP 403: {raw_resp[:512]}")
  364. if status_code == 429:
  365. self.is_healthy = False
  366. raise RateLimiteddError(f"HTTP 429: {raw_resp[:512]}")
  367. raise BizLogicError(f"HTTP {status_code} error. resp={raw_resp[0:512]}")
  368. # 5. 解析返回的数据
  369. available_dates = []
  370. match = re.search(r'(\{.*\})', raw_resp, re.DOTALL)
  371. if match:
  372. json_str = match.group(1)
  373. data = json.loads(json_str)
  374. else:
  375. data = json.loads(raw_resp)
  376. schedule_days = data.get("ScheduleDays", [])
  377. if schedule_days:
  378. for day_obj in schedule_days:
  379. date_str = day_obj.get("Date")
  380. if date_str:
  381. available_dates.append(date_str)
  382. # 6. 处理最终结果 (保持与你原有返回结构一致)
  383. if available_dates:
  384. # 确保日期是有序的
  385. available_dates.sort()
  386. res.success = True
  387. res.availability_status = AvailabilityStatus.Available
  388. earliest_date = available_dates[0]
  389. res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d")
  390. res.availability = [
  391. DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
  392. for d in available_dates
  393. ]
  394. self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
  395. else:
  396. res.success = False
  397. res.availability_status = AvailabilityStatus.NoneAvailable
  398. self._log("No slots available.")
  399. return res
  400. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  401. """进行预约操作"""
  402. res = VSBookResult()
  403. res.success = False
  404. exp_start = user_inputs.get('expected_date_start', '')
  405. exp_end = user_inputs.get('expected_date_end', '')
  406. available_dates_str =[
  407. da.date.strftime("%Y-%m-%d")
  408. for da in slot_info.availability if da.date
  409. ]
  410. valid_dates_list = self._filter_dates(available_dates_str, exp_start, exp_end)
  411. if not valid_dates_list:
  412. raise NotFoundError(message="No dates match user constraints")
  413. selected_slot_date = random.choice(valid_dates_list)
  414. book_date_obj = datetime.strptime(selected_slot_date, "%Y-%m-%d").date()
  415. # jQuery UI Datepicker 月份是 0-11
  416. target_day = str(book_date_obj.day)
  417. target_month = str(book_date_obj.month - 1)
  418. target_year = str(book_date_obj.year)
  419. self._log(f"Target booking date: {selected_slot_date}. Navigating calendar...")
  420. # 1. 适配不在当前日历的情况:通过下拉框选择年份和月份
  421. year_select = self.page.ele('.ui-datepicker-year', timeout=10) # 查找年份下拉框
  422. if year_select and year_select.value != target_year:
  423. self._log(f"Changing year to {target_year}")
  424. year_select.select.by_value(target_year)
  425. self._random_sleep(0.5, 1)
  426. month_select = self.page.ele('.ui-datepicker-month', timeout=10) # 查找月份下拉框
  427. if month_select and month_select.value != target_month:
  428. self._log(f"Changing month to {target_month}")
  429. month_select.select.by_value(target_month)
  430. self._random_sleep(0.5, 1)
  431. # 2. 点击目标日期
  432. self._log(f"Clicking date {selected_slot_date}...")
  433. target_cell_selector = f"xpath://td[@data-year='{target_year}' and @data-month='{target_month}']//a[text()='{target_day}']"
  434. target_date_cell = self.page.ele(target_cell_selector, timeout=10)
  435. if not target_date_cell:
  436. raise BizLogicError(f"Target date element not found for {selected_slot_date} after navigating.")
  437. self.mouse.human_click_ele(target_date_cell)
  438. self._log("Waiting for available times to load...")
  439. self._random_sleep(3, 5)
  440. # 3. 等待并选择时间
  441. self._log("Selecting earliest available time...")
  442. slot_time_selector = "css:#time_select input[name='schedule-entries']"
  443. first_time_radio = self.page.ele(slot_time_selector, timeout=15)
  444. if not first_time_radio:
  445. raise BizLogicError("Failed to load time slots after clicking date. Might be rate limited or slots gone.")
  446. selected_slot_time = first_time_radio.parent().text.strip()
  447. self.mouse.human_click_ele(first_time_radio)
  448. # 4. 点击提交
  449. self._random_sleep(1, 2)
  450. self._log("Submitting booking...")
  451. submit_appointment_selector = "#submitbtn"
  452. submit_button = self.page.ele(submit_appointment_selector, timeout=10)
  453. self.mouse.human_click_ele(submit_button)
  454. self._log("Booking submitted successfully!")
  455. # 构造返回结果
  456. res = VSBookResult()
  457. res.success = True
  458. res.book_date = selected_slot_date
  459. res.book_time = selected_slot_time
  460. res.account = self.config.account.username
  461. return res
  462. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  463. if not start_str or not end_str:
  464. return dates
  465. valid_dates = []
  466. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  467. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  468. for date_str in dates:
  469. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  470. if s_date <= curr_date <= e_date:
  471. valid_dates.append(date_str)
  472. random.shuffle(valid_dates)
  473. return valid_dates
  474. # --- 资源清理核心方法 ---
  475. def cleanup(self):
  476. """
  477. 销毁浏览器并彻底删除临时文件
  478. """
  479. if self.page:
  480. try:
  481. self.page.quit(force=True)
  482. except Exception:
  483. pass
  484. self.page = None
  485. if os.path.exists(self.root_workspace):
  486. for _ in range(3):
  487. try:
  488. time.sleep(0.2)
  489. shutil.rmtree(self.root_workspace, ignore_errors=True)
  490. break
  491. except Exception as e:
  492. self._log(f"Cleanup retry: {e}")
  493. time.sleep(0.5)
  494. if os.path.exists(self.root_workspace):
  495. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  496. if self.tunnel:
  497. try: self.tunnel.stop()
  498. except: pass
  499. self.tunnel = None
  500. def __del__(self):
  501. """
  502. 析构函数:当对象被垃圾回收时自动调用
  503. """
  504. self.cleanup()