### Example 2: Element Finding Setup Source: https://0xshoulderlab.site/automation/overview Provides necessary imports and basic setup for element finding examples, including OS and IO modules. This serves as boilerplate for the subsequent examples. ```python # -*- coding: utf-8 -*- """ 示例2: 元素查找 测试功能: - CSS选择器查找 - XPath查找 - 文本查找 - 属性查找 - 多元素查找 - 元素属性获取 """ import os import sys import io ``` -------------------------------- ### Quickstart Cloudflare and Copilot Example Source: https://0xshoulderlab.site/automation/anti-bot A Python script demonstrating how to access a high-risk site, automatically handle Cloudflare challenges, identify input fields, send a query, and extract cookies. It includes setup for FirefoxOptions and uses RuyiPage APIs for navigation and interaction. ```python # ============================= # RuyiPage 示例注释版 # 标题: Cloudflare / Copilot 快速开始 # 说明: 面向高风控站点的快速开始示例,覆盖挑战处理、输入框识别和 Cookie 提取。 # 你会学到: # 1. 访问高风控站点并等待页面完成首屏加载 # 2. 自动尝试处理 Cloudflare 挑战 # 3. 定位输入框并发送问题 # 4. 提取 document.cookie 与完整 Cookie 信息 # 相关 API: FirefoxOptions, FirefoxPage, page.get, page.ele, page.handle_cloudflare_challenge, page.get_cookies # ============================= # -*- coding: utf-8 -*-"""快速开始:访问 Copilot,自动尝试通过 Cloudflare,并打印完整 Cookie。""" from ruyipage import FirefoxOptions, FirefoxPage, Keys QUESTION = "你好,今天天气怎么样?" def find_input_box(page: FirefoxPage): for _ in range(30): box = page.ele("css:textarea") if not box: box = page.ele('css:[contenteditable="true"]') if not box: box = page.ele("css:.input-area") if box: return box page.wait(1) return None def print_full_cookies(page: FirefoxPage) -> None: print("\n" + "=" * 60) print("Cloudflare / 页面 Cookie") print("=" * 60) raw_cookie = page.run_js("return document.cookie") or "" print(f"document.cookie: {raw_cookie}") cookies = page.get_cookies(all_info=True) print(f"Cookie 数量: {len(cookies)}") for i, cookie in enumerate(cookies, 1): print(f"[{i}] name={cookie.name}") print(f" value={cookie.value}") print(f" domain={cookie.domain}") print(f" path={cookie.path}") print(f" httpOnly={cookie.http_only}") print(f" secure={cookie.secure}") print(f" sameSite={cookie.same_site}") print(f" expiry={cookie.expiry}") opts = FirefoxOptions() # 如果 Firefox 不在默认安装目录,可以取消注释并指定路径。 # opts.set_browser_path(r"D:\Firefox\firefox.exe") # 如果你想复用登录状态、Cookie、扩展,可以取消注释并指定 userdir。 # opts.set_user_dir(r"D:\ruyipage_userdir") page = FirefoxPage(opts) try: print("=" * 60) print("copilot.microsoft.com Cloudflare 测试") print("=" * 60) print("\n-> 访问 https://copilot.microsoft.com/ ...") page.get("https://copilot.microsoft.com/", wait="none") page.wait(5) print("-> 等待输入框...") input_box = find_input_box(page) if input_box: print("-> 找到输入框,开始输入问题...") try: input_box.click() page.wait(0.8) input_box.input(QUESTION, clear=True) page.wait(0.8) send_btn = page.ele('css:button[aria-label*="Send"]') if not send_btn: send_btn = page.ele('css:button[type="submit"]') if send_btn: print("-> 点击发送按钮...") send_btn.click() else: print("-> 按 Enter 发送...") page.actions.press(Keys.ENTER).perform() print("-> 已发送问题,等待 Cloudflare 触发...") page.wait(15) except Exception as e: print(f"-> 发送失败: {e}") page.wait(5) else: print("-> 未找到输入框,直接等待 Cloudflare...") page.wait(5) print("\n-> 开始自动处理 Cloudflare...") passed = page.handle_cloudflare_challenge(timeout=120, check_interval=2) print("\n" + "=" * 60) if passed: print("✅ 成功通过 Cloudflare!") print_full_cookies(page) else: print("❌ 超时未通过") print("\n[+] 保持浏览器打开 500 秒...") page.wait(500) finally: page.quit() ``` -------------------------------- ### RuyiPage Scrolling Example Setup Source: https://0xshoulderlab.site/automation/examples Initial setup and imports for the scrolling demonstration script. ```python # ============================= # RuyiPage 示例注释版 # 标题: 滚动操作:页面滚动、容器滚动、滚动到元素 # 说明: 围绕滚轮和滚动可见性组织的一组常见交互。 # 你会学到: # 1. 滚动到页面顶部与底部 # 2. 按像素距离滚动 # 3. 滚动直到目标元素进入视口 # 4. 控制容器内部滚动 # 5. 读取滚动位置用于调试 # 相关 API: page.actions.scroll, page.scroll.to_bottom, page.scroll.to_top, page.scroll.to_see, ele.scroll.to_bottom, ele.scroll.to_top, states.is_in_viewport # ============================= # -*- coding: utf-8 -*- """ 示例10: 滚动操作 测试功能: - 滚动到顶部/底部 - 滚动到元素 - 滚动指定距离 - 元素内滚动 """ import os import sys import io ``` -------------------------------- ### Launch Firefox and Get Page Title Source: https://0xshoulderlab.site/automation A minimal 'hello-world' example to verify environment setup and establish a basic understanding. It demonstrates launching Firefox, navigating to a page, waiting for stability, and retrieving the page title and H1 text. ```python # ============================= # RuyiPage 示例注释版 # 标题: 一步上手:最少代码完成访问与读取 # 说明: 最短可运行的 hello-world 级别示例,适合验证环境和建立第一层心智模型。 # 你会学到: # 1. 用 launch() 启动 Firefox # 2. 访问网页并等待页面稳定 # 3. 读取标题和 H1 文本 # 4. 演示最短退出流程 # 相关 API: launch, page.get, page.wait, page.title, page.ele, ele.text, page.quit # ============================= # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) print(f"标题: {page.title}") h1 = page.ele("tag:h1") print(f"H1文本: {h1.text}") print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` ```python # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) print(f"标题: {page.title}") h1 = page.ele("tag:h1") print(f"H1文本: {h1.text}") print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` -------------------------------- ### Cloudflare / Copilot Quick Start Example Source: https://0xshoulderlab.site/automation/anti-bot A quick start example for high-risk control sites, covering challenge handling, input box identification, and cookie extraction. ```APIDOC ## Cloudflare / Copilot Quick Start This example demonstrates how to visit a high-risk website (Copilot), automatically handle Cloudflare challenges, identify and interact with input fields, and extract cookies. ### Key Learnings: * Visiting high-risk sites and waiting for initial page load. * Automatically attempting to resolve Cloudflare challenges. * Locating input fields and sending queries. * Extracting `document.cookie` and full cookie information. ### Related APIs: * `FirefoxOptions` * `FirefoxPage` * `page.get` * `page.ele` * `page.handle_cloudflare_challenge` * `page.get_cookies` ### Source Code (`app/content/ruyipage_examples/quickstart_cloudfare.py`) ```python # ============================= # RuyiPage Example Annotated Version # Title: Cloudflare / Copilot Quick Start # Description: Quick start example for high-risk control sites, covering challenge handling, input box identification, and cookie extraction. # You will learn: # 1. Visit high-risk sites and wait for initial page load # 2. Automatically attempt to resolve Cloudflare challenges # 3. Locate input fields and send queries # 4. Extract document.cookie and full cookie information # Related APIs: FirefoxOptions, FirefoxPage, page.get, page.ele, page.handle_cloudflare_challenge, page.get_cookies # ============================= # -*- coding: utf-8 -*- """Quick start: Visit Copilot, automatically attempt to pass Cloudflare, and print full cookies.""" from ruyipage import FirefoxOptions, FirefoxPage, Keys QUESTION = "你好,今天天气怎么样?" def find_input_box(page: FirefoxPage): for _ in range(30): box = page.ele("css:textarea") if not box: box = page.ele('css:[contenteditable="true"]') if not box: box = page.ele("css:.input-area") if box: return box page.wait(1) return None def print_full_cookies(page: FirefoxPage) -> None: print("\n" + "=" * 60) print("Cloudflare / Page Cookies") print("=" * 60) raw_cookie = page.run_js("return document.cookie") or "" print(f"document.cookie: {raw_cookie}") cookies = page.get_cookies(all_info=True) print(f"Number of Cookies: {len(cookies)}") for i, cookie in enumerate(cookies, 1): print(f"[{i}] name={cookie.name}") print(f" value={cookie.value}") print(f" domain={cookie.domain}") print(f" path={cookie.path}") print(f" httpOnly={cookie.http_only}") print(f" secure={cookie.secure}") print(f" sameSite={cookie.same_site}") print(f" expiry={cookie.expiry}") opts = FirefoxOptions() # If Firefox is not in the default installation directory, uncomment and specify the path. # opts.set_browser_path(r"D:\Firefox\firefox.exe") # If you want to reuse login status, cookies, or extensions, uncomment and specify userdir. # opts.set_user_dir(r"D:\ruyipage_userdir") page = FirefoxPage(opts) try: print("=" * 60) print("copilot.microsoft.com Cloudflare Test") print("=" * 60) print("\n-> Visiting https://copilot.microsoft.com/ ...") page.get("https://copilot.microsoft.com/", wait="none") page.wait(5) print("-> Waiting for input box...") input_box = find_input_box(page) if input_box: print("-> Input box found, starting to type question...") try: input_box.click() page.wait(0.8) input_box.input(QUESTION, clear=True) page.wait(0.8) send_btn = page.ele('css:button[aria-label*="Send"]') if not send_btn: send_btn = page.ele('css:button[type="submit"]') if send_btn: print("-> Clicking send button...") send_btn.click() else: print("-> Pressing Enter to send...") page.actions.press(Keys.ENTER).perform() print("-> Question sent, waiting for Cloudflare trigger...") page.wait(15) except Exception as e: print(f"-> Failed to send: {e}") page.wait(5) else: print("-> Input box not found, waiting for Cloudflare directly...") page.wait(5) print("\n-> Starting automatic Cloudflare handling...") passed = page.handle_cloudflare_challenge(timeout=120, check_interval=2) print("\n" + "=" * 60) if passed: print("✅ Successfully passed Cloudflare!") print_full_cookies(page) else: print("❌ Timed out without passing") print("\n[+] Keeping browser open for 500 seconds...") page.wait(500) finally: page.quit() ``` ``` -------------------------------- ### Initialize RuyiPage Script Example Source: https://0xshoulderlab.site/automation/examples?example=network-events-31 Boilerplate setup for the RuyiPage script example demonstrating advanced capabilities. ```python #!/usr/bin/env python # ============================= # RuyiPage 示例注释版 # 标题: Script 与 Input 高级能力:realms、handle 回收、文件输入 # 说明: 连接 script 与 input 的高级能力,是 script 页的重要支撑示例。 # 你会学到: # 1. 获取全部和 window 类型 realms # 2. 执行脚本得到远程对象句柄 # 3. 回收单个和批量 handle # 4. 利用 file input 上传单文件和多文件 # 相关 API: page.get_realms, page.eval_handle, page.disown_handles, ele.input # ============================= ``` -------------------------------- ### Quickstart: Basic Page Access and Interaction Source: https://0xshoulderlab.site/automation/examples?example=advanced-input-20 A minimal example to verify the environment by launching a browser, navigating to a page, and reading element text. ```python # ============================= # RuyiPage 示例注释版 # 标题: 一步上手:最少代码完成访问与读取 # 说明: 最短可运行的 hello-world 级别示例,适合验证环境和建立第一层心智模型。 # 你会学到: # 1. 用 launch() 启动 Firefox # 2. 访问网页并等待页面稳定 # 3. 读取标题和 H1 文本 # 4. 演示最短退出流程 # 相关 API: launch, page.get, page.wait, page.title, page.ele, ele.text, page.quit # ============================= # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) print(f"标题: {page.title}") h1 = page.ele("tag:h1") print(f"H1文本: {h1.text}") print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` ```python # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) print(f"标题: {page.title}") h1 = page.ele("tag:h1") print(f"H1文本: {h1.text}") print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` -------------------------------- ### Initialize Navigation Events Example Source: https://0xshoulderlab.site/automation/examples?example=elements-02 Boilerplate setup for the RuyiPage navigation events example script. ```python #!/usr/bin/env python # ============================= # RuyiPage 示例注释版 # 标题: 导航事件:started、load、fragment、history、committed、failed # 说明: 导航事件链路的标准参考示例。 # 你会学到: # 1. 订阅导航生命周期事件 # 2. 观察 navigationStarted、DOMContentLoaded 和 load # 3. 观察 hash 片段跳转 # 4. 观察 History API 更新 # 5. 构造失败导航场景 # 相关 API: page.navigation.start, page.navigation.wait, page.navigation.wait_for_load, page.navigation.wait_for_fragment, page.navigation.stop # ============================= ``` -------------------------------- ### RuyiPage Window Management Example Source: https://0xshoulderlab.site/automation/examples?example=comprehensive-15 Initial setup and imports for the RuyiPage window management example script. ```python # ============================= # RuyiPage 示例注释版 # 标题: 窗口管理:尺寸、位置、状态流与标签切换 # 说明: 系统覆盖 window 与 viewport 的浏览器级操作。 # 你会学到: # 1. 读取窗口和视口尺寸 # 2. 调整窗口大小与位置 # 3. 切换最大化、最小化、全屏等状态 # 4. 多标签创建和激活切换 # 相关 API: page.rect.window_size, page.rect.viewport_size, page.rect.window_location, page.rect.page_size, page.window.maximize, page.window.minimize, page.window.fullscreen, page.window.set_size # ============================= # -*- coding: utf-8 -*- """示例16: 浏览器窗口管理(完整场景) 测试覆盖: 1) 窗口/视口/页面尺寸与位置 2) 窗口状态流:normal -> maximize -> minimize -> fullscreen -> normal 3) 设置窗口大小、位置、居中 4) 多标签创建、激活、切换、关闭 """ import os import sys import io ``` -------------------------------- ### Quickstart: Basic Page Access and Reading Source: https://0xshoulderlab.site/automation/examples?example=basic-navigation-01 This is the shortest runnable example, suitable for verifying the environment and establishing a basic understanding. It covers launching Firefox, visiting a page, waiting for stability, and reading the title and H1 text. ```python # ============================= # RuyiPage 示例注释版 # 标题: 一步上手:最少代码完成访问与读取 # 说明: 最短可运行的 hello-world 级别示例,适合验证环境和建立第一层心智模型。 # 你会学到: # 1. 用 launch() 启动 Firefox # 2. 访问网页并等待页面稳定 # 3. 读取标题和 H1 文本 # 4. 演示最短退出流程 # 相关 API: launch, page.get, page.wait, page.title, page.ele, ele.text, page.quit # ============================= # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) print(f"标题: {page.title}") h1 = page.ele("tag:h1") print(f"H1文本: {h1.text}") print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` -------------------------------- ### Setup Download Directory and Server Source: https://0xshoulderlab.site/automation/downloads Prepares the download directory by removing existing files and creating a new one. It also starts a test server to serve content for download tests. ```python download_path = os.path.abspath("E:/ruyipage/examples/downloads") text_path = os.path.join(download_path, "test.txt") json_path = os.path.join(download_path, "test.json") if os.path.exists(download_path): shutil.rmtree(download_path) os.makedirs(download_path, exist_ok=True) server = TestServer(port=find_free_port(8930, 9030)).start() base_url = server.get_url("")[:-1] ``` -------------------------------- ### Quickstart: Launch, Navigate, and Read Source: https://0xshoulderlab.site/automation/examples?example=quickstart-01 This is the shortest runnable example for verifying your environment and understanding basic RuyiPage usage. It covers launching Firefox, navigating to a URL, reading the page title and H1 text, and closing the browser. ```python # ============================= # RuyiPage 示例注释版 # 标题: 一步上手:最少代码完成访问与读取 # 说明: 最短可运行的 hello-world 级别示例,适合验证环境和建立第一层心智模型。 # 你会学到: # 1. 用 launch() 启动 Firefox # 2. 访问网页并等待页面稳定 # 3. 读取标题和 H1 文本 # 4. 演示最短退出流程 # 相关 API: launch, page.get, page.wait, page.title, page.ele, ele.text, page.quit # ============================= # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) print(f"标题: {page.title}") h1 = page.ele("tag:h1") print(f"H1文本: {h1.text}") print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` ```python # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) print(f"标题: {page.title}") h1 = page.ele("tag:h1") print(f"H1文本: {h1.text}") print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` -------------------------------- ### Setup and Teardown for Test Server Source: https://0xshoulderlab.site/automation/examples?example=comprehensive-15 Initializes and starts a test server on a free port within a specified range. Ensures the server is properly started before proceeding with network tests. ```python server = TestServer(port=find_free_port(9230, 9330)).start() base_url = server.get_url("" )[:-1] ``` -------------------------------- ### Basic Scrolling Example Setup Source: https://0xshoulderlab.site/automation/examples?example=native-select-36 This Python code sets up the necessary imports and comments for a scrolling example. It includes standard library imports and UTF-8 encoding. ```python # ============================= # RuyiPage 示例注释版 # 标题: 滚动操作:页面滚动、容器滚动、滚动到元素 # 说明: 围绕滚轮和滚动可见性组织的一组常见交互。 # 你会学到: # 1. 滚动到页面顶部与底部 # 2. 按像素距离滚动 # 3. 滚动直到目标元素进入视口 # 4. 控制容器内部滚动 # 5. 读取滚动位置用于调试 # 相关 API: page.actions.scroll, page.scroll.to_bottom, page.scroll.to_top, page.scroll.to_see, ele.scroll.to_bottom, ele.scroll.to_top, states.is_in_viewport # ============================= # -*- coding: utf-8 -*- """ 示例10: 滚动操作 测试功能: - 滚动到顶部/底部 - 滚动到元素 - 滚动指定距离 - 元素内滚动 """ import os import sys import io ``` -------------------------------- ### Example: Quickstart Demo Source: https://0xshoulderlab.site/automation/page A minimal Python script demonstrating the basic usage of RuyiPage, including launching the browser, navigating to a URL, reading the title, and interacting with an element. ```APIDOC ## Example: Quickstart Demo ### Description This example provides the shortest possible runnable code to verify your environment setup and build a foundational understanding of RuyiPage. ### Method Python script execution ### Endpoint N/A ### Parameters None ### Request Example ```python # -*- coding: utf-8 -*- """ 示例01: 一步上手 面向新手:最少代码完成一次页面访问与元素交互。 """ import io import sys if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import launch def quickstart_demo(): print("=" * 60) print("示例01: 一步上手") print("=" * 60) page = launch(headless=False) try: page.get("https://example.com") page.wait(1) # Assuming page.wait exists for demonstration print(f"标题: {page.title}") h1 = page.ele("tag:h1") # Assuming page.ele exists for demonstration print(f"H1文本: {h1.text}") # Assuming ele.text exists for demonstration print("\n✓ 快速上手完成") finally: page.wait(1) page.quit() if __name__ == "__main__": quickstart_demo() ``` ### Response #### Success Response (200) Prints the page title and the text content of the first H1 element to the console. #### Response Example ``` ============================================================ 示例01: 一步上手 ============================================================ 标题: Example Domain H1文本: Example Domain ✓ 快速上手完成 ``` ### Related APIs `launch`, `page.get`, `page.wait`, `page.title`, `page.ele`, `ele.text`, `page.quit` ``` -------------------------------- ### JavaScript Execution and Scripting Source: https://0xshoulderlab.site/automation/examples?example=advanced-input-20 Initial setup for JavaScript execution examples, including imports and configuration. ```python # ============================= # RuyiPage 示例注释版 # 标题: JavaScript 执行与脚本能力 # 说明: 展示 run_js、参数传递、DOM 修改和 preload script 的调试价值。 # 你会学到: # 1. 执行表达式并获取返回值 # 2. 向脚本传参 # 3. 直接修改 DOM 内容 # 4. 在元素上下文执行 JS # 5. 读取 realms 并注入 preload script # 相关 API: page.run_js, ele.run_js, page.get_realms, page.eval_handle, page.add_preload_script, page.remove_preload_script # ============================= # -*- coding: utf-8 -*- """ 示例7: JavaScript执行 测试功能: - 执行JavaScript代码 - 获取返回值 - 传递参数 - 在元素上执行JS - 修改页面内容 """ import os import sys import io ``` -------------------------------- ### Manage Web Extensions with RuyiPage Source: https://0xshoulderlab.site/automation/examples?tab=repo This example covers the installation, verification of content script injection, and uninstallation of browser extensions using RuyiPage. It demonstrates installing from a directory, packaging and installing an XPI file, and clearing test extensions. ```python #!/usr/bin/env python # ============================= # RuyiPage 示例注释版 # 标题: WebExtension:目录扩展与 XPI 安装卸载 # 说明: 覆盖扩展安装、验证注入和卸载,是浏览器级能力的重要专题。 # 你会学到: # 1. 安装目录扩展 # 2. 验证 content script 生效 # 3. 打包并安装 XPI 扩展 # 4. 卸载指定扩展与清空测试扩展 # 相关 API: page.extensions.install, page.extensions.install_archive, page.extensions.uninstall, page.extensions.uninstall_all, page.run_js # ============================= ``` -------------------------------- ### Initialize RuyiPage Tab Management Script Source: https://0xshoulderlab.site/automation/examples?example=elements-03 Boilerplate setup for the tab management example script. ```python # ============================= # RuyiPage 示例注释版 # 标题: 标签页管理:新建、切换、查找、关闭、后台激活 # 说明: 展示 tab 作为日常页面操作的重要组织单位。 # 你会学到: # 1. 新建标签页并加载地址 # 2. 通过标题、索引等方式查找 tab # 3. 获取所有标签页 ID # 4. 激活后台标签页 # 5. 关闭单个标签或保留当前标签关闭其他标签 # 相关 API: page.new_tab, page.tabs_count, page.tab_ids, page.get_tab, page.get_tabs, page.latest_tab, page.close_other_tabs, page.browser.activate_tab # ============================= # -*- coding: utf-8 -*- """ 示例9: 标签页管理 测试功能: - 新建标签页 - 切换标签页 - 关闭标签页 - 获取标签页列表 - 标签页操作 """ import os import sys import io ``` -------------------------------- ### Cloudflare/Copilot Quick Start (Python) Source: https://0xshoulderlab.site/automation/examples?example=advanced-input-20 An advanced example for high-risk websites, demonstrating how to handle Cloudflare challenges, identify input fields, and extract cookies. ```python # ============================= # RuyiPage 示例注释版 # 标题: Cloudflare / Copilot 快速开始 # 说明: 面向高风控站点的快速开始示例,覆盖挑战处理、输入框识别和 Cookie 提取。 # 你会学到: # 1. 访问高风控站点并等待页面完成首屏加载 # 2. 自动尝试处理 Cloudflare 挑战 # 3. 定位输入框并发送问题 # 4. 提取 document.cookie 与完整 Cookie 信息 # 相关 API: FirefoxOptions, FirefoxPage, page.get, page.ele, page.handle_cloudflare_challenge, page.get_cookies # ============================= ``` -------------------------------- ### Setup for BrowsingContext Events Source: https://0xshoulderlab.site/automation/examples?example=elements-03 Initializes the FirefoxPage and sets up stdout/stderr for UTF-8 encoding on Windows. This is boilerplate for the example. ```python import io import sys from typing import Dict, List if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import BidiEvent, FirefoxPage ``` -------------------------------- ### Cloudflare / Copilot Quick Start (Python) Source: https://0xshoulderlab.site/automation/examples An advanced example for high-risk websites, demonstrating how to handle Cloudflare challenges, identify input fields, and extract cookies. ```python # ============================= # RuyiPage 示例注释版 # 标题: Cloudflare / Copilot 快速开始 # 说明: 面向高风控站点的快速开始示例,覆盖挑战处理、输入框识别和 Cookie 提取。 # 你会学到: # 1. 访问高风控站点并等待页面完成首屏加载 # 2. 自动尝试处理 Cloudflare 挑战 # 3. 定位输入框并发送问题 # 4. 提取 document.cookie 与完整 Cookie 信息 # 相关 API: FirefoxOptions, FirefoxPage, page.get, page.ele, page.handle_cloudflare_challenge, page.get_cookies # ============================= ``` -------------------------------- ### Setup and Helper Functions Source: https://0xshoulderlab.site/automation/examples?example=waits-04 Initializes the testing environment and defines utility functions for managing test results. Includes platform-specific stdout/stderr configuration. ```python import io import sys from typing import Dict, List if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import FirefoxPage, InterceptedRequest from ruyipage._functions.tools import find_free_port from test_server import TestServer def add_result( results: List[Dict[str, str]], item: str, status: str, note: str ) -> None: results.append({"item": item, "status": status, "note": note}) def print_results(results: List[Dict[str, str]]) -> None: print("\n| 项目 | 状态 | 说明 |") print("| --- | --- | --- |") for row in results: print(f"| {row['item']} | {row['status']} | {row['note']} |") ``` -------------------------------- ### Example 12: Console Listener Test Setup Source: https://0xshoulderlab.site/automation/examples?example=native-select-36 Provides the necessary imports and basic structure for running console listener tests. It includes standard library imports for system operations and I/O. ```python # -*- coding: utf-8 -*- """ Example 12: Console Listener Test functions: - Listen to console.log - Listen to console.error - Listen to console.warn - Get log content """ import os import sys import io ``` -------------------------------- ### Install and Verify XPI Extension Source: https://0xshoulderlab.site/automation/examples?tab=all Installs an XPI extension, verifies its activation by checking for content script injection, and then uninstalls it. This process is skipped if extension installation fails. ```python # 7) 验证 XPI 扩展已生效 if ext_id2: page.get("https://example.com") page.wait(1.5) marker = _page_has_extension_marker(page) rows.add( "XPI 扩展生效验证", "✓ 通过" if marker else "✗ 失败", "content script 已注入" if marker else "未检测到注入标记", ) else: rows.add("XPI 扩展生效验证", "⚠ 跳过", "安装未成功") # 8) 卸载打包扩展 if ext_id2: page.extensions.uninstall(ext_id2) rows.add("卸载 XPI 扩展", "✓ 通过") else: rows.add("卸载 XPI 扩展", "⚠ 跳过", "未安装成功") print("\n" + "=" * 70) print("✓ WebExtension 模块测试完成") print("=" * 70) except Exception as e: rows.add("WebExtension 模块", "✗ 失败", str(e)) import traceback traceback.print_exc() finally: try: page.extensions.uninstall_all() except Exception: pass page.quit() if os.path.exists(ext_dir): shutil.rmtree(ext_dir) if os.path.exists(xpi_path): os.remove(xpi_path) rows.add("清理测试文件", "✓ 通过") rows.summary() if __name__ == "__main__": test_web_extension() ``` -------------------------------- ### Test Actions Chain Setup Source: https://0xshoulderlab.site/automation/examples?tab=all This is the main function to test various automated web actions. It includes setup, execution of different action types, and cleanup. ```python def test_actions_chain(): try: # ... (previous code for drag and drop) print("\n" + "=" * 60) print("✓ 所有动作链测试通过!") print("=" * 60) except Exception as e: print(f"\n✗ 测试失败: {e}") import traceback traceback.print_exc() finally: page.wait(2) page.quit() if __name__ == "__main__": test_actions_chain() ``` -------------------------------- ### Test WebExtension Installation and Verification Source: https://0xshoulderlab.site/automation/examples?tab=all This function tests the installation, verification, and uninstallation of an XPI extension. It includes steps for checking browser compatibility, installing the extension, verifying its functionality by checking for injected content scripts, and finally uninstalling it. Cleanup of temporary files and browser instances is handled in the finally block. ```python def test_web_extension(): try: # ... (previous code omitted for brevity) # 7) 验证 XPI 扩展已生效 if ext_id2: page.get("https://example.com") page.wait(1.5) marker = _page_has_extension_marker(page) rows.add( "XPI 扩展生效验证", "✓ 通过" if marker else "✗ 失败", "content script 已注入" if marker else "未检测到注入标记", ) else: rows.add("XPI 扩展生效验证", "⚠ 跳过", "安装未成功") # 8) 卸载打包扩展 if ext_id2: page.extensions.uninstall(ext_id2) rows.add("卸载 XPI 扩展", "✓ 通过") else: rows.add("卸载 XPI 扩展", "⚠ 跳过", "未安装成功") print("\n" + "=" * 70) print("✓ WebExtension 模块测试完成") print("=" * 70) except Exception as e: rows.add("WebExtension 模块", "✗ 失败", str(e)) import traceback traceback.print_exc() finally: try: page.extensions.uninstall_all() except Exception: pass page.quit() if os.path.exists(ext_dir): shutil.rmtree(ext_dir) if os.path.exists(xpi_path): os.remove(xpi_path) rows.add("清理测试文件", "✓ 通过") rows.summary() if __name__ == "__main__": test_web_extension() ``` -------------------------------- ### Setup and Helper Functions Source: https://0xshoulderlab.site/automation/examples?tab=repo Initializes FirefoxPage and defines helper functions for recording and printing test results. Includes platform-specific stdout/stderr encoding for Windows. ```python import io import sys from typing import Dict, List if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") from ruyipage import FirefoxPage def add_result( results: List[Dict[str, str]], item: str, status: str, note: str ) -> None: """记录结构化结果。""" results.append({"item": item, "status": status, "note": note}) def print_results(results: List[Dict[str, str]]) -> None: """打印固定格式结果表。""" print("\n| 项目 | 状态 | 说明 |") print("| --- | --- | --- |") for row in results: print(f"| {row['item']} | {row['status']} | {row['note']} |") ```