""" Cloudflare 挑战自动化穿透工具模块。 针对 Cloudflare Turnstile / 5秒盾(Managed Challenge)提供高效、稳定的穿透能力。 核心设计理念: 1. 快速精准定位:定向穿透隐藏 turnstile input 对应的 shadow_root 宿主容器及嵌套 iframe, 无需遍历全局 DOM,执行耗时 < 0.2s。 2. 异常自愈回退:提供可控深度的 DFS 备用探测策略。 3. 等待室自适应排队:支持 Waiting Room 自动轮询处理。 4. 代码风格标准:严格遵循 Pythonic 规范,杜绝使用 hasattr,保证属性访问安全与可维护性。 """ import time from typing import Optional, Callable from DrissionPage import ChromiumPage from DrissionPage._elements.chromium_element import ChromiumElement class CloudflareBypasser: """ Cloudflare 页面挑战识别与穿透处理器 """ def __init__( self, driver: ChromiumPage, log: bool = False, logger: Optional[Callable[[str], None]] = None ) -> None: self.driver = driver self.log = log self.logger = logger def log_message(self, message: str) -> None: """统一日志输出辅助方法""" if not self.log: return formatted = f"[CF-Bypass] {message}" if self.logger: if callable(self.logger): try: self.logger(formatted) except TypeError: self.logger(message) else: log_fn = getattr(self.logger, "info", print) log_fn(formatted) else: print(formatted) def _extract_turnstile_button_from_host(self, host_ele: Optional[ChromiumElement]) -> Optional[ChromiumElement]: """ 从挂载 Shadow Root 的宿主容器元素中提取 Turnstile 复选框按钮。 DOM 层级链路: Host Element (div) └─ shadow_root └─ child (iframe) └─ body └─ shadow_root └─ input[type=checkbox] """ if not host_ele: return None orig_timeout = getattr(getattr(self.driver, "timeouts", None), "base", 2) try: if hasattr(self.driver, "set") and hasattr(self.driver.set, "timeouts"): self.driver.set.timeouts(base=0.3) host_sr = getattr(host_ele, "shadow_root", None) if not host_sr: return None iframe = host_sr.child(timeout=0.3) if not iframe: return None body = iframe("tag:body", timeout=0.3) if not body: return None body_sr = getattr(body, "shadow_root", None) if not body_sr: return None return body_sr("tag:input", timeout=0.3) except Exception as e: self.log_message(f"Error extracting button from host element: {e}") return None finally: if hasattr(self.driver, "set") and hasattr(self.driver.set, "timeouts"): self.driver.set.timeouts(base=orig_timeout) def locate_cf_button(self, dfs: bool = False) -> Optional[ChromiumElement]: """ 定位 Cloudflare 验证复选框按钮。 策略 1(主路径,毫秒级):扫描主文档中的 'cf-turnstile-response' 隐藏 input, 其前置同级兄弟 div 或父级容器即为真实 shadow_root 宿主,直接提取目标按钮。 策略 2(备用路径):若主路径未命中且显式开启 dfs=True,则从 body 递归搜索。 """ try: # --- 策略 1: 基于隐藏 Turnstile input 的定向穿透 --- eles = self.driver.eles("tag:input") for ele in eles: attrs = getattr(ele, "attrs", {}) name = attrs.get("name", "") inp_type = attrs.get("type", "") if "turnstile" in name and inp_type == "hidden": parent = ele.parent() if not parent: continue # 优先检查同级前置兄弟
(在大多数现代 Turnstile 结构中该 div 才是 shadow_root 宿主) host_candidates = [] sibling_div = parent.ele("tag:div", timeout=0.3) if sibling_div: host_candidates.append(sibling_div) host_candidates.append(parent) for candidate in host_candidates: button = self._extract_turnstile_button_from_host(candidate) if button: self.log_message("Target verification button located via Turnstile host div.") return button # --- 策略 2: 备用递归深度搜索 (DFS) --- if dfs: self.log_message("Basic search missed. Initiating fallback DFS...") body = self.driver.ele("tag:body") if body: iframe = self.search_recursively_shadow_root_with_iframe(body) if iframe: iframe_body = iframe("tag:body") if iframe_body: return self.search_recursively_shadow_root_with_cf_input(iframe_body) return None except Exception as e: self.log_message(f"Error locating verification button: {e}") return None def search_recursively_shadow_root_with_iframe( self, ele: Optional[ChromiumElement], depth: int = 0, max_depth: int = 3 ) -> Optional[ChromiumElement]: """递归检索挂载在 shadow_root 下的 iframe""" if depth > max_depth or not ele: return None try: sr = getattr(ele, "shadow_root", None) if sr: child = sr.child() if child and getattr(child, "tag", "") == "iframe": return child else: children = getattr(ele, "children", None) if callable(children): for child in children(): result = self.search_recursively_shadow_root_with_iframe(child, depth + 1, max_depth) if result: return result except Exception: pass return None def search_recursively_shadow_root_with_cf_input( self, ele: Optional[ChromiumElement] ) -> Optional[ChromiumElement]: """递归检索挂载在 shadow_root 下的目标 input 按钮""" if not ele: return None try: sr = getattr(ele, "shadow_root", None) if sr: inp = sr.ele("tag:input") if inp: return inp else: children = getattr(ele, "children", None) if callable(children): for child in children(): result = self.search_recursively_shadow_root_with_cf_input(child) if result: return result except Exception: pass return None def click_verification_button(self, is_dfs: bool = False) -> bool: """ 定位并执行点击 Cloudflare 验证按钮。 :return: 是否成功点击 """ try: button = self.locate_cf_button(dfs=is_dfs) if not button: self.log_message("Verification button not found.") return False states = getattr(button, "states", None) displayed = getattr(states, "is_displayed", False) if states else False enabled = getattr(states, "is_enabled", False) if states else False if displayed and enabled: self.log_message("Verification button clickable. Executing click...") button.click() time.sleep(1.0) self.log_message("Click executed successfully.") return True else: self.log_message(f"Button found (<{button.tag}>) but unclickable (displayed={displayed}, enabled={enabled}).") return False except Exception as e: self.log_message(f"Error clicking verification button: {e}") return False def is_bypassed(self) -> bool: """ 根据当前页面标题判断是否已经脱离 Cloudflare 挑战页面。 """ try: title = (getattr(self.driver, "title", "") or "").lower() return "just a moment" not in title and "请稍候" not in title except Exception as e: self.log_message(f"Error checking page title: {e}") return False def bypass(self, max_retry: int = 5, use_dfs: bool = False) -> bool: """ 执行穿透循环直至挑战通过或达到最大重试次数。 """ for i in range(max_retry): if self.is_bypassed(): self.log_message("Cloudflare challenge bypassed successfully.") return True self.log_message(f"Verification page detected. Attempting bypass (try {i + 1}/{max_retry})...") self.click_verification_button(is_dfs=use_dfs) time.sleep(2.0) final_bypassed = self.is_bypassed() if final_bypassed: self.log_message("Cloudflare challenge bypassed on final check.") else: self.log_message(f"[WARN] Failed to clear challenge after {max_retry} attempts.") return final_bypassed def handle_waiting_room(self, max_wait_sec: int = 3600) -> bool: """ 检测并等待 Cloudflare 等候室(Waiting Room)自动刷新放行。 """ wait_start = time.time() while time.time() - wait_start < max_wait_sec: try: html = (getattr(self.driver, "html", "") or "").lower() if "cloudflare" not in html: return True if any(w in html for w in ["file d'attente", "waitting room", "waiting room"]): self.log_message("In Waiting Room... Waiting for queue to refresh (sleeping 10s)...") time.sleep(10.0) else: return True except Exception as e: self.log_message(f"Error checking html in waiting room: {e}") break return True