Просмотр исходного кода

feat: initialize page1.txt and page2.txt with portal configuration and boilerplate assets

jerry 2 месяцев назад
Родитель
Сommit
f406e18d15
3 измененных файлов с 0 добавлено и 379 удалено
  1. 0 94
      robotics (副本)/README.md
  2. 0 123
      robotics (副本)/cf_bypasser.py
  3. 0 162
      robotics (副本)/tls_flow.py

+ 0 - 94
robotics (副本)/README.md

@@ -1,94 +0,0 @@
-# TLScontact 签证预约自动化系统 (DrissionPage 注解流驱动)
-
-本项目基于 **DrissionPage** 与 **声明式注解状态机(Annotation-Driven Flow)** 架构,专为 TLScontact 等复杂多步骤、带 Cloudflare 挑战与动态页面流转的签证预约场景设计。
-
----
-
-## 🌟 核心特性
-
-1. **声明式注解架构**:
-   - `@on(url=..., title=..., ele=..., not_ele=..., priority=...)`:声明页面状态与触发动作。
-   - `@guard(...)`:高优先级异常守卫(处理 502/504、Cloudflare Challenge、Session 过期)。
-   - `@fatal(...)`:命中特定错误(如未添加申请人、账号锁定)时立即终止。
-   - `@done`:命中成功终态时自动提交并成功退出。
-2. **Cloudflare 自动穿透**:
-   - 自动识别 Cloudflare Turnstile / 5秒盾挑战,穿透 iframe 与 DOM 节点进行拟人化点击,带人工兜底。
-3. **开箱即用内置 Chromium**:
-   - 自动优先检测并加载项目目录自带的 `ungoogled-chromium-148.0.7778.215-1-x86_64_linux/chrome`,无需复杂安装。
-4. **内置 Mock 模拟测试**:
-   - 提供内置轻量 Mock 服务,一键进行全链路离线模拟测试,验证各状态转移与规则调度。
-5. **健壮防卡死自愈**:
-   - 内置步数扫描、停滞检测与页面自愈刷新机制。
-
----
-
-## 📁 目录结构
-
-```
-.
-├── config.yaml          # 运行时主配置文件
-├── config.example.yaml  # 配置文件模板
-├── flow_annotated.py    # 注解流驱动核心引擎 (BaseFlow, @on, @guard, @done, @fatal)
-├── cf_bypasser.py       # Cloudflare Turnstile / 5秒盾自动绕过模块
-├── tls_flow.py          # TLScontact 业务流程状态机实现 (TlsContactFlow)
-├── mock_server.py       # 本地离线 Mock 服务端
-├── main.py              # 主程序命令行启动入口
-├── requirements.txt     # Python 依赖清单
-└── ungoogled-chromium-* # 内置免安装 Chromium 浏览器
-```
-
----
-
-## 🚀 快速开始
-
-### 1. 安装依赖
-
-```bash
-pip install -r requirements.txt
-```
-
-### 2. 一键离线 Mock 模拟测试 (推荐优先尝试)
-
-无需配置真实账号或连接外部网络,运行本地模拟测试:
-
-```bash
-# 无头模式快速测试
-python main.py --mock --headless
-
-# 有头模式可视化测试 (观察浏览器真实点击与跳转)
-python main.py --mock
-```
-
-### 3. 正式生产环境运行
-
-编辑 `config.yaml` 填写您的实际信息:
-
-```yaml
-auth:
-  username: "your_email@example.com"
-  password: "your_secure_password"
-
-target:
-  url: "https://visas-de.tlscontact.com/visa/gb/gbLON2de/home"
-  login_url: "https://visas-de.tlscontact.com/visa/gb/gbLON2de/login"
-
-flow:
-  interval: 1.0
-  max_steps: 45
-  preferred_dates:
-    - "2026-09"
-```
-
-启动正式流程:
-
-```bash
-python main.py
-```
-
-### 4. 命令行参数支持
-
-- `--mock` / `--test`:启动本地 Mock 服务进行端到端测试。
-- `--headless`:强制使用无头模式运行。
-- `--config <path>`:指定自定义配置文件路径(默认 `config.yaml`)。
-- `--username <user>` / `--password <pwd>`:命令行覆盖账号密码。
-- `--url <url>`:命令行覆盖目标入口 URL。

+ 0 - 123
robotics (副本)/cf_bypasser.py

@@ -1,123 +0,0 @@
-"""
-cf_bypasser.py - Cloudflare Turnstile / 5秒盾 自动识别与穿透辅助工具
-支持 DrissionPage iframe / Shadow DOM 拟人化穿透与人工兜底机制
-"""
-
-import time
-from typing import Optional, Callable
-
-
-class CloudflareBypasser:
-    def __init__(self, page, logger=None, max_wait_sec: int = 15):
-        """
-        :param page: DrissionPage 的 ChromiumPage 实例
-        :param logger: 日志记录器
-        :param max_wait_sec: 最大等待绕过时间(秒)
-        """
-        self.page = page
-        self.max_wait_sec = max_wait_sec
-        self._raw_logger = logger
-
-    def log(self, msg: str, level: str = "info"):
-        if self._raw_logger:
-            if callable(self._raw_logger):
-                try:
-                    self._raw_logger(msg, level=level)
-                except TypeError:
-                    self._raw_logger(msg)
-            else:
-                log_fn = getattr(self._raw_logger, level.lower(), getattr(self._raw_logger, "info", print))
-                log_fn(msg)
-        else:
-            print(f"[CloudflareBypasser] {msg}")
-
-    def is_challenge_present(self) -> bool:
-        """检查当前页面是否存在 Cloudflare 挑战盾"""
-        try:
-            title = (getattr(self.page, "title", "") or "").lower()
-            if any(t in title for t in ["just a moment", "cloudflare", "attention required", "security check"]):
-                return True
-
-            # 检查是否有 CF 相关的特征元素或 iframe
-            if self.page.ele("@src:challenges.cloudflare.com", timeout=0.2):
-                return True
-            if self.page.ele(".cf-turnstile", timeout=0.2) or self.page.ele("@class:cf-turnstile", timeout=0.2):
-                return True
-            if self.page.ele("#challenge-running", timeout=0.2) or self.page.ele("#challenge-stage", timeout=0.2):
-                return True
-        except Exception:
-            pass
-        return False
-
-    def _click_turnstile_checkbox(self) -> bool:
-        """尝试穿透 iframe 和 shadow DOM 点击 Turnstile 验证框"""
-        # 1. 寻找 challenges.cloudflare.com 的 iframe
-        try:
-            cf_iframes = self.page.eles("@src:challenges.cloudflare.com", timeout=0.5)
-            for iframe in cf_iframes:
-                try:
-                    btn = iframe.ele("tag:input@type=checkbox", timeout=0.5) or \
-                          iframe.ele(".mark", timeout=0.5) or \
-                          iframe.ele("@class:spacer", timeout=0.5) or \
-                          iframe.ele("tag:body", timeout=0.5)
-                    if btn:
-                        self.log("🔍 检测到 Turnstile 验证框 iframe,正在执行拟人化点击...")
-                        time.sleep(0.6)
-                        btn.click()
-                        time.sleep(1.0)
-                        return True
-                except Exception as e:
-                    self.log(f"尝试穿透 iframe 元素点击失败: {e}")
-        except Exception:
-            pass
-
-        # 2. 检查本页直接挂载的 Turnstile / Challenge 元素
-        try:
-            turnstile_container = self.page.ele(".cf-turnstile", timeout=0.5) or \
-                                  self.page.ele("@class:cf-turnstile", timeout=0.5) or \
-                                  self.page.ele("#turnstile-box", timeout=0.5) or \
-                                  self.page.ele("@id:turnstile", timeout=0.5)
-            if turnstile_container:
-                self.log("🔍 检测到本页 Turnstile 容器,尝试直接点击...")
-                turnstile_container.click()
-                time.sleep(1.0)
-                return True
-        except Exception:
-            pass
-
-        return False
-
-    def bypass(self) -> bool:
-        """
-        执行穿透挑战流程
-        :return: 是否成功通过
-        """
-        self.log("🛡️ 检测到 Cloudflare 挑战页面,启动自动穿透流程...")
-        start_time = time.time()
-
-        # 先稍作等待,部分挑战是纯 JS 静默计算
-        time.sleep(0.8)
-
-        while time.time() - start_time < self.max_wait_sec:
-            if not self.is_challenge_present():
-                self.log("✅ Cloudflare 挑战已成功通过!")
-                return True
-
-            # 尝试查找并点击
-            clicked = self._click_turnstile_checkbox()
-            if clicked:
-                self.log("🖱️ 已触发点击验证框,等待验证结果...")
-                time.sleep(1.5)
-                if not self.is_challenge_present():
-                    self.log("✅ Cloudflare 挑战已成功通过!")
-                    return True
-
-            time.sleep(0.8)
-
-        # 超时后再次检查
-        if not self.is_challenge_present():
-            self.log("✅ Cloudflare 挑战已通过!")
-            return True
-
-        self.log("⚠️ 自动穿透超时,若处于有头浏览器模式,请在窗口中手动完成验证...", level="warning")
-        return False

+ 0 - 162
robotics (副本)/tls_flow.py

@@ -1,162 +0,0 @@
-"""
-tls_flow.py - TLScontact 签证预约业务流程状态机
-基于 BaseFlow 声明式注解,实现异常自愈、登录、申请人流转与时段监控
-"""
-
-import time
-from flow_annotated import BaseFlow, on, done, fatal, guard
-from cf_bypasser import CloudflareBypasser
-
-
-class TlsContactFlow(BaseFlow):
-    def __init__(self, page, config=None, interval=1.0, logger=None, cf_bypasser=None):
-        super().__init__(page, config=config, interval=interval, logger=logger, cf_bypasser=cf_bypasser)
-        if self.cf_bypasser is None:
-            self.cf_bypasser = CloudflareBypasser(page, logger=self.log)
-        self.preferred_dates = self.config.get("preferred_dates", [])
-
-    # -----------------------------------------------------------------------
-    # 1. 异常守卫注解 (高优先级 priority=1~20)
-    # -----------------------------------------------------------------------
-    @guard(text="502 Bad Gateway", priority=5)
-    def on_502_error(self):
-        self.log("[WARN] 检测到 502 网关错误,等待 3 秒后刷新重试...", level="warning")
-        time.sleep(3)
-        self.page.refresh()
-
-    @guard(text="504 Gateway Time-out", priority=5)
-    def on_504_error(self):
-        self.log("[WARN] 检测到 504 网关超时,等待 3 秒后刷新重试...", level="warning")
-        time.sleep(3)
-        self.page.refresh()
-
-    @guard(title="just a moment", priority=6)
-    def on_cloudflare_challenge_title(self):
-        self.log("🛡️ 命中 Cloudflare Challenge 守卫 (Title 匹配)...")
-        self.cf_bypasser.bypass()
-
-    @guard(ele="@src:challenges.cloudflare.com", priority=6)
-    def on_cloudflare_challenge_iframe(self):
-        self.log("🛡️ 命中 Cloudflare Turnstile 守卫 (Iframe 匹配)...")
-        self.cf_bypasser.bypass()
-
-    @guard(text="Session Expired", priority=8)
-    def on_session_expired(self):
-        self.log("[WARN] 会话已过期,重新跳转至登录入口...", level="warning")
-        login_url = self.config.get("login_url") or self.config.get("target_url")
-        if login_url:
-            self.page.get(login_url)
-
-    # -----------------------------------------------------------------------
-    # 2. 致命错误注解 (直接中断)
-    # -----------------------------------------------------------------------
-    @on(text="You have not yet added an applicant", priority=15)
-    @fatal("未找到申请人,请先在官网完善申请人基本信息后再次执行!")
-    def on_no_applicant(self):
-        pass
-
-    @on(text="Account locked", priority=15)
-    @fatal("账号已被锁定,请稍后再试或联系 TLScontact 客服!")
-    def on_account_locked(self):
-        pass
-
-    # -----------------------------------------------------------------------
-    # 3. 业务表单操作 (登录、分组、概览、预约时段)
-    # -----------------------------------------------------------------------
-    @on(ele="tag:label@text():Email", priority=50)
-    def handle_login_by_label(self):
-        self.log("正在填写登录表单 (通过 Label 查找)...")
-        username = self.config.get("username", "")
-        password = self.config.get("password", "")
-        
-        email_input = self.page.ele('tag:label@text():Email').next('tag:input') or self.page.ele('tag:input@type=email') or self.page.ele('@name=email')
-        if email_input:
-            email_input.clear()
-            email_input.input(username)
-        
-        pwd_input = self.page.ele('tag:label@text():Password').next('tag:input') or self.page.ele('tag:input@type=password') or self.page.ele('@name=password')
-        if pwd_input:
-            pwd_input.clear()
-            pwd_input.input(password)
-
-        time.sleep(0.5)
-        login_btn = self.page.ele('tag:button@text():Login') or self.page.ele('tag:button@type=submit')
-        if login_btn:
-            login_btn.click()
-
-    @on(url="/login", ele="tag:input@type=email", priority=51)
-    def handle_login_by_url(self):
-        self.log("正在填写登录页面...")
-        username = self.config.get("username", "")
-        password = self.config.get("password", "")
-        
-        self.page.ele('tag:input@type=email').input(username)
-        self.page.ele('tag:input@type=password').input(password)
-        time.sleep(0.5)
-        self.page.ele('tag:button@type=submit').click()
-
-    @on(url="travel-groups", priority=60)
-    def handle_travel_groups(self):
-        self.log("正在选择行程/申请人分组...")
-        btn = self.page.ele('tag:button@name=formGroupId') or \
-              self.page.ele('tag:button@text():Select') or \
-              self.page.ele('.group-btn') or \
-              self.page.ele('tag:a@text():View')
-        if btn:
-            btn.click()
-        else:
-            self.log("[WARN] 未找到分组按钮,尝试点击列表首项...")
-            card = self.page.ele('.group-card')
-            if card:
-                card.click()
-
-    @on(url="application-summary", priority=70)
-    def handle_change_booking(self):
-        self.log("正在处理申请人摘要页 (application-summary)...")
-        change_btn = self.page.ele('tag:button@text():Change') or self.page.ele('tag:button@text():Book')
-        if change_btn:
-            change_btn.click()
-            time.sleep(0.5)
-        
-        # 确认弹窗
-        yes_btn = self.page.ele('tag:button@text():Yes') or self.page.ele('tag:button@text():Confirm')
-        if yes_btn:
-            yes_btn.click()
-
-    @on(url="appointment-booking", ele=".available-slot", priority=80)
-    def handle_slot_selection(self):
-        self.log("📅 发现可用预约时段,正在选择最优时段...")
-        slots = self.page.eles(".available-slot") or self.page.eles(".slot-btn")
-        if slots:
-            selected_slot = slots[0]
-            for slot in slots:
-                slot_text = slot.text
-                if any(pref in slot_text for pref in self.preferred_dates):
-                    selected_slot = slot
-                    self.log(f"🎯 命中首选日期时段: {slot_text}")
-                    break
-            
-            selected_slot.click()
-            time.sleep(0.5)
-            
-            confirm_btn = self.page.ele("tag:button@text():Confirm Slot") or self.page.ele("tag:button@text():Continue")
-            if confirm_btn:
-                confirm_btn.click()
-
-    # -----------------------------------------------------------------------
-    # 4. 成功终态注解 (Done)
-    # -----------------------------------------------------------------------
-    @on(url="appointment-booking", ele="tag:button@text():Book your appointment", priority=30)
-    @done
-    def on_booking_button_submit(self):
-        self.log("🎯 点击最终预约提交按钮...")
-        btn = self.page.ele("tag:button@text():Book your appointment")
-        if btn:
-            btn.click()
-        self.log("✅ 抢号/预约流程提交完成!")
-
-    @on(url="appointment-confirmation", priority=25)
-    @on(text="Appointment Confirmed", priority=25)
-    @done
-    def on_booking_success_confirmed(self):
-        self.log("🎉 页面已跳转至预约成功确认页!预约成功!")