### Agent Usage Examples Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Basic and advanced configuration examples for the Agent class. ```python # 基础用法 agent = Agent( interface=WebPage(page), model="qwen-vl-max" ) # 完整配置 agent = Agent( interface=WebPage(page), model="qwen-vl-max", api_key="your-api-key", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", cache_id="production_test", cache_strategy="read-write", enable_recording=True, temperature=0.1, max_tokens=8192 ) ``` -------------------------------- ### Install PyMidscene Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md Install the package and required Playwright browser binaries. ```bash pip install pymidscene # 安装 Playwright 浏览器 playwright install chromium ``` ```bash poetry add pymidscene playwright install chromium ``` -------------------------------- ### WebPage Integration Example Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Example showing how to wrap a Playwright page with the WebPage adapter. ```python from playwright.async_api import async_playwright from pymidscene.web_integration.playwright import WebPage async with async_playwright() as p: browser = await p.chromium.launch() page = await browser.new_page() # 创建 WebPage 适配器 web_page = WebPage( page, wait_for_navigation_timeout=5000, wait_for_network_idle_timeout=10000 ) # 使用适配器 screenshot = await web_page.screenshot() await web_page.click(640, 360) ``` -------------------------------- ### Install PyMidscene and dependencies Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Commands to clone the repository, install the package in editable mode, and set up the required Playwright browser. ```bash # 克隆项目 git clone https://github.com/yourusername/pymidscene.git cd pymidscene # 安装依赖 pip install -e . # 安装 Playwright 浏览器 playwright install chromium ``` -------------------------------- ### Quick Start iOS Automation Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/ios/README.md Initialize the iOS environment and use the agent to perform basic interactions like launching apps and AI-driven taps. ```python import asyncio from pymidscene.ios import agent_from_webdriver_agent, check_ios_environment async def main(): env = await check_ios_environment() assert env["available"], env["error"] async with await agent_from_webdriver_agent() as agent: await agent.launch("微信") # 中文名 → com.tencent.xin await agent.ai_tap("扫一扫") await agent.ai_query({"text": "页面标题"}) await agent.home() asyncio.run(main()) ``` -------------------------------- ### Install pymidscene Android dependencies Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/android/README.md Install the package and verify ADB connectivity. ```bash pip install "pymidscene[android]" # 首次使用前确认 adb 可用 adb devices ``` -------------------------------- ### Quick start with pymidscene Android agent Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/android/README.md Initialize an agent from an ADB device and perform basic automation tasks. ```python import asyncio from pymidscene.android import agent_from_adb_device async def main(): agent = await agent_from_adb_device() # 自动选第一个在线设备 await agent.launch("小红书") await agent.ai_tap("搜索框") await agent.ai_input("搜索框", "Python") print(await agent.ai_query({"titles": "前 5 条笔记标题"})) agent.finish() asyncio.run(main()) ``` -------------------------------- ### Initialize WebDriver Agent Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/webdriver/README.md Example of how the future WebDriver integration will be initialized with a Selenium driver and a PyMidscene Agent. ```python from pymidscene import Agent from pymidscene.webdriver import WebDriverPage from selenium import webdriver # 初始化 WebDriver driver = webdriver.Chrome() web_page = WebDriverPage(driver) # 创建 Agent(支持多种模型) agent = Agent(web_page, model="qwen-vl-max") # 或 "doubao-vision" # 执行自动化 driver.get("https://example.com") agent.ai_act("点击登录按钮") ``` -------------------------------- ### Waiting Strategy Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Example of using explicit waits to ensure page state before assertions. ```python await agent.ai_click("提交按钮") await asyncio.sleep(2) # 等待页面加载 await agent.ai_assert("显示成功提示") ``` -------------------------------- ### Example Cache YAML Structure Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md The format used for storing cached locate operations. ```yaml caches: - type: locate prompt: 搜索框 cache: bbox: [100, 200, 300, 250] - type: locate prompt: 搜索按钮 cache: bbox: [400, 200, 500, 250] ``` -------------------------------- ### Execute complex AI actions Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Examples of using ai_action to perform multi-step interactions or tasks requiring autonomous scrolling and element location. ```python # 执行复杂交互(AI 自动处理滚动、点击等) await agent.ai_action("点击自主声明选项的下拉选择框") # AI 会自动处理元素不在视口中的情况 # 发现目标不可见 → 规划 Scroll → 滚动后重新截图 → 找到元素后操作 await agent.ai_action("选择下拉菜单中的 虚拟演绎 选项") # 多步骤任务 await agent.ai_action("在搜索框中输入 Python 并点击搜索按钮") ``` -------------------------------- ### Write Automation Script Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md Example of using PlaywrightAgent to perform browser interactions and data extraction via natural language. ```python import asyncio import os from playwright.async_api import async_playwright from pymidscene import PlaywrightAgent async def main(): # 配置模型(或使用环境变量) os.environ["MIDSCENE_MODEL_NAME"] = "doubao-seed-1-6-251015" os.environ["MIDSCENE_MODEL_API_KEY"] = "your-api-key" os.environ["MIDSCENE_MODEL_BASE_URL"] = "https://ark.cn-beijing.volces.com/api/v3" os.environ["MIDSCENE_MODEL_FAMILY"] = "doubao-vision" async with async_playwright() as p: browser = await p.chromium.launch(headless=False) page = await browser.new_page() # 创建 agent,可选启用缓存 agent = PlaywrightAgent(page, cache_id="my_task") # 导航到页面 await page.goto("https://www.baidu.com") # 使用自然语言进行交互 await agent.ai_click("搜索输入框") await agent.ai_input("搜索框", "Python 自动化") await agent.ai_click("百度一下按钮") # 提取数据 result = await agent.ai_query({ "results_count": "搜索结果数量", "first_title": "第一条结果的标题" }) print(f"结果: {result}") # 断言页面状态 await agent.ai_assert("页面显示了搜索结果") # 生成可视化报告 report_path = agent.finish() print(f"报告已保存到: {report_path}") await browser.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Perform AI-assisted scrolling Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Examples of using ai_scroll to navigate pages using different scroll types and target element prompts. ```python # 向下滚动 await agent.ai_scroll("down", 500) # 滚动到页面底部 await agent.ai_scroll(scroll_type="scrollToBottom") # 在特定元素上滚动 await agent.ai_scroll("down", 300, locate_prompt="商品列表区域") ``` -------------------------------- ### Wait for page conditions Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Examples of using ai_wait_for to pause execution until specific page states or elements are detected. ```python # 等待页面加载完成 await agent.ai_wait_for("页面显示了笔记管理", timeout=30) # 等待元素出现 await agent.ai_wait_for("标题输入框已出现", timeout=15) # 自定义轮询间隔 await agent.ai_wait_for("上传进度达到 100%", timeout=60, interval=3) ``` -------------------------------- ### Initialize WebPage Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Constructor signature for the WebPage adapter. ```python WebPage( page: PlaywrightPage, wait_for_navigation_timeout: Optional[int] = None, wait_for_network_idle_timeout: Optional[int] = None ) ``` -------------------------------- ### Initialize Agent and perform AI automation Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Demonstrates setting up an Agent with a Playwright page, performing input and click actions, and querying data from the page. ```python import asyncio from playwright.async_api import async_playwright from pymidscene.core.agent import Agent from pymidscene.web_integration.playwright import WebPage async def main(): async with async_playwright() as p: browser = await p.chromium.launch(headless=False) page = await browser.new_page() # 创建 Agent agent = Agent( interface=WebPage(page), model="qwen-vl-max", cache_id="my_test" ) # 访问网页 await page.goto("https://www.baidu.com") # AI 自动化操作 await agent.ai_input("搜索框", "Python 教程") await agent.ai_click("搜索按钮") # 提取数据 result = await agent.ai_query({ "title": "页面标题,字符串", "count": "搜索结果数量,数字" }) print(result['data']) await browser.close() asyncio.run(main()) ``` -------------------------------- ### 配置环境变量文件 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/MODELS.md 在 .env 文件中定义模型名称、API 密钥、基础 URL 和模型家族。 ```bash # 豆包模型 MIDSCENE_MODEL_NAME=your-endpoint-id MIDSCENE_MODEL_API_KEY=your-api-key MIDSCENE_MODEL_BASE_URL=https://ark.cn-beijing.volces.com/api/v3 MIDSCENE_MODEL_FAMILY=doubao-vision ``` -------------------------------- ### Initialize Agent Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Constructor signature for the Agent class. ```python Agent( interface: AbstractInterface, model: str = "qwen-vl-max", api_key: Optional[str] = None, base_url: Optional[str] = None, cache_id: Optional[str] = None, cache_strategy: str = "read-write", cache_dir: Optional[str] = None, enable_recording: bool = False, **model_kwargs ) ``` -------------------------------- ### Element Location Best Practices Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Demonstrates recommended descriptive queries versus vague or technical selectors. ```python # 推荐 await agent.ai_locate("登录按钮") await agent.ai_locate("页面右上角的用户头像") await agent.ai_locate("第一个搜索结果的标题") # 避免 await agent.ai_locate("按钮") # 太模糊 await agent.ai_locate("div") # 使用技术术语 ``` -------------------------------- ### Agent Model Parameters Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Initializes the Agent with specific model settings like temperature and token limits. ```python agent = Agent( interface=web_page, model="qwen-vl-max", temperature=0.1, # 温度(0-1) max_tokens=8192, # 最大 tokens top_p=0.95, # Top-p 采样 ) ``` -------------------------------- ### 配置 OpenAI GPT-4V 环境变量 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/MODELS.md 设置 OpenAI GPT-4V 模型的接入参数。 ```bash MIDSCENE_MODEL_NAME=gpt-4-vision-preview MIDSCENE_MODEL_API_KEY=sk-xxxxxx MIDSCENE_MODEL_BASE_URL=https://api.openai.com/v1 MIDSCENE_MODEL_FAMILY=openai ``` -------------------------------- ### 实现坐标适配函数 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 在 utils 中添加坐标转换逻辑,根据模型类型自动选择适配方式。 ```python def adapt_doubao_bbox(bbox, width, height): """Doubao 模型归一化坐标转换""" return ( round(bbox[0] * width / 1000), round(bbox[1] * height / 1000), round(bbox[2] * width / 1000), round(bbox[3] * height / 1000), ) def adapt_bbox(bbox, width, height, model_family): """根据模型类型自动选择转换方式""" if model_family in ('doubao-vision', 'vlm-ui-tars-doubao'): return adapt_doubao_bbox(bbox, width, height) elif model_family == 'gemini': return adapt_gemini_bbox(bbox, width, height) elif model_family == 'qwen2.5-vl': return adapt_qwen_bbox(bbox) else: return normalized_0_1000(bbox, width, height) ``` -------------------------------- ### 运行自动化测试脚本 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 执行完整功能验证测试。 ```bash cd pymidscene python tests/validation/test_automation.py ``` -------------------------------- ### Agent Initialization Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Configures and initializes the AI Agent with model parameters and caching strategies. ```APIDOC ## Agent(interface, model, temperature, max_tokens, top_p, cache_id, cache_strategy) ### Description Initializes the agent with specific model settings and caching configurations. ### Parameters - **interface** (WebPage) - Required - The web page interface instance. - **model** (str) - Optional - The AI model to use (e.g., "qwen-vl-max"). - **temperature** (float) - Optional - Sampling temperature (0-1). - **max_tokens** (int) - Optional - Maximum tokens for the response. - **top_p** (float) - Optional - Top-p sampling parameter. - **cache_id** (str) - Optional - Identifier for caching. - **cache_strategy** (str) - Optional - Caching strategy (e.g., "read-write", "read-only"). ``` -------------------------------- ### Data Extraction Best Practices Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Shows how to provide explicit type hints in queries for better extraction results. ```python # 明确类型 result = await agent.ai_query({ "title": "页面标题,字符串", "price": "商品价格,数字", "count": "评论数量,整数" }) # 类型不明确 result = await agent.ai_query({ "title": "标题", "price": "价格" }) ``` -------------------------------- ### 通过 model_config 参数配置 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/MODELS.md 在初始化 Agent 时传入配置字典。 ```python config = { "MIDSCENE_MODEL_NAME": "your-endpoint-id", "MIDSCENE_MODEL_API_KEY": "your-api-key", "MIDSCENE_MODEL_BASE_URL": "https://...", "MIDSCENE_MODEL_FAMILY": "doubao-vision", } agent = PlaywrightAgent(page, model_config=config) ``` -------------------------------- ### Enable Execution Recording Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Configure the Agent to capture execution logs by setting enable_recording to True. ```python agent = Agent( interface=web_page, model="qwen-vl-max", enable_recording=True ) ``` -------------------------------- ### 项目目录结构 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/ARCHITECTURE.md PyMidscene 项目的源代码组织结构,包含核心模块、Web 集成、共享工具及各平台适配器。 ```text pymidscene/ ├── __init__.py # 包入口,导出主要 API ├── core/ # 核心模块 │ ├── agent/ # Agent 实现 │ │ ├── agent.py # 主 Agent 类 │ │ └── task_cache.py # 缓存系统(XPath 缓存) │ ├── ai_model/ # AI 模型集成 │ │ ├── __init__.py # 模型调用入口 │ │ ├── models/ # 具体模型适配器 │ │ │ ├── doubao.py # 豆包模型 │ │ │ └── qwen.py # 千问模型 │ │ └── prompts/ # Prompt 模板 │ │ ├── locator.py # 元素定位 Prompt │ │ └── extractor.py # 数据提取 Prompt │ ├── dump.py # 执行记录和报告生成 │ ├── report_generator.py # HTML 报告生成器 │ └── types.py # 类型定义 ├── web_integration/ # Web 集成 │ ├── base.py # 抽象接口定义 │ └── playwright/ # Playwright 适配器 │ ├── agent.py # PlaywrightAgent │ └── page.py # WebPage 适配器 ├── shared/ # 共享工具 │ ├── logger.py # 日志系统 │ ├── types.py # 共享类型 │ ├── utils.py # 工具函数 │ └── env.py # 环境变量管理 ├── android/ # Android 支持(待开发) ├── ios/ # iOS 支持(待开发) └── webdriver/ # Selenium 支持(待开发) ``` -------------------------------- ### Configure Agent Caching Strategies Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Initialize the Agent with different cache strategies to control read/write behavior during development or CI/CD. ```python # 启用缓存 agent = Agent( interface=web_page, cache_id="my_test", cache_strategy="read-write" ) # 只读模式(CI/CD) agent = Agent( interface=web_page, cache_id="ci_test", cache_strategy="read-only" ) # 只写模式(强制重新生成) agent = Agent( interface=web_page, cache_id="rebuild", cache_strategy="write-only" ) ``` -------------------------------- ### 检查截图与视口尺寸 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 用于排查坐标偏移是否由坐标归一化问题引起。 ```python # 如果截图 1280x800,视口也是 1280x800,但坐标偏移 # 说明是坐标归一化问题,不是 DPR 缩放问题 ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Configures API keys and logging levels via environment variables. ```bash # 千问 API 配置 export MIDSCENE_QWEN_API_KEY="your-api-key" export MIDSCENE_QWEN_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" # 日志级别 export MIDSCENE_LOG_LEVEL="DEBUG" # DEBUG, INFO, WARNING, ERROR ``` -------------------------------- ### 开发环境设置与测试 Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md 用于克隆仓库、安装开发依赖、运行测试及格式化代码的命令行指令。 ```bash # 开发环境设置 git clone https://github.com/AIPythoner/pymidscene.git cd pymidscene pip install -e ".[dev]" # 运行测试 pytest # 格式化代码 black pymidscene tests ``` -------------------------------- ### Configure API Environment Variables Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md Set environment variables for supported AI models to enable Midscene functionality. ```bash # 豆包模型(推荐国内用户使用) export MIDSCENE_MODEL_NAME="doubao-seed-1-6-251015" export MIDSCENE_MODEL_API_KEY="your-api-key" export MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" export MIDSCENE_MODEL_FAMILY="doubao-vision" # 千问模型 export MIDSCENE_MODEL_NAME="qwen-vl-max" export MIDSCENE_MODEL_API_KEY="your-api-key" export MIDSCENE_MODEL_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" export MIDSCENE_MODEL_FAMILY="qwen2.5-vl" ``` -------------------------------- ### 处理动态内容 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md 通过设置 use_cache=False 参数禁用缓存,以获取页面的实时状态。 ```python element = await agent.ai_locate("实时股价", use_cache=False) ``` -------------------------------- ### 检查模型类型坐标格式 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 记录不同模型返回的坐标格式差异。 ```python # 不同模型返回的坐标格式不同 # doubao-vision: 归一化 0-1000 # qwen2.5-vl: 像素坐标 # gemini: [y1, x1, y2, x2] 归一化 0-1000 ``` -------------------------------- ### Project Documentation Directory Structure Source: https://github.com/aipythoner/pymidscene/blob/main/docs/README.md Visual representation of the project's documentation file hierarchy. ```text docs/ ├── API.md # API 参考文档 ├── ARCHITECTURE.md # 架构设计(方便继续开发) ├── TROUBLESHOOTING.md # 故障排查指南 └── MODELS.md # 支持的模型配置 ``` -------------------------------- ### 配置千问模型环境变量 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/MODELS.md 设置阿里云 DashScope 千问模型的接入参数。 ```bash MIDSCENE_MODEL_NAME=qwen-vl-max MIDSCENE_MODEL_API_KEY=sk-xxxxxx MIDSCENE_MODEL_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 MIDSCENE_MODEL_FAMILY=qwen2.5-vl ``` -------------------------------- ### Configure ADBKeyboard for non-ASCII input Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/android/README.md Enable and set the ADBKeyboard input method on the Android device. ```bash adb shell ime enable com.android.adbkeyboard/.AdbIME adb shell ime set com.android.adbkeyboard/.AdbIME ``` -------------------------------- ### 坐标系统适配逻辑 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/PORTING_PROGRESS.md 根据不同的模型家族对边界框坐标进行转换,确保坐标格式与目标模型兼容。 ```python def adapt_bbox(bbox, width, height, model_family): if model_family == "doubao-vision": # 归一化 0-1000 -> 像素 return adapt_doubao_bbox(bbox, width, height) elif model_family == "gemini": # [y1,x1,y2,x2] -> [x1,y1,x2,y2] return adapt_gemini_bbox(bbox, width, height) else: return bbox ``` -------------------------------- ### Agent(enable_recording=True) Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Enables execution recording for the Agent to track tasks, screenshots, and AI usage. ```APIDOC ## Agent Initialization (Recording) ### Description Enables the recording feature to capture execution logs, including screenshots and token usage. ### Parameters - **enable_recording** (boolean) - Optional - Set to True to enable logging. ``` -------------------------------- ### Implement WebDriverPage Interface Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/webdriver/README.md Template for the required methods that must be implemented to integrate Selenium WebDriver with the PyMidscene core. ```python class WebDriverPage(AbstractInterface): def screenshot(self) -> str: """返回 Base64 编码的截图""" pass def get_size(self) -> Size: """获取页面尺寸""" pass def click(self, x: float, y: float): """点击指定坐标""" pass def input_text(self, x: float, y: float, text: str): """在指定位置输入文本""" pass ``` -------------------------------- ### Define Cache File Path Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md The default location for stored cache files. ```text .midscene/cache/.cache.yaml ``` -------------------------------- ### 配置豆包模型环境变量 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/MODELS.md 设置火山引擎豆包模型的接入点和密钥。 ```bash MIDSCENE_MODEL_NAME=ep-20250122xxxxxx # 你的 Endpoint ID MIDSCENE_MODEL_API_KEY=your-api-key MIDSCENE_MODEL_BASE_URL=https://ark.cn-beijing.volces.com/api/v3 MIDSCENE_MODEL_FAMILY=doubao-vision ``` -------------------------------- ### Execute Verification Commands Source: https://github.com/aipythoner/pymidscene/blob/main/docs/FIX_PROGRESS_2026-04-17.md Commands to verify report generation and run non-e2e unit tests within the pymidscene project environment. ```bash # 报告验证(AGENTS.md §Commit/Release Workflow Rules) cd pymidscene && venv/Scripts/python.exe -m pytest \ tests/core/test_report_template_resources.py \ tests/core/test_js_react_report_generator.py \ tests/core/test_session_recorder_report_fallback.py \ tests/test_integration.py::TestReportTemplateCompatibility::test_agent_finish_uses_packaged_report_template_resources \ tests/packaging/report_smoke.py -q # 非 e2e 单测 cd pymidscene && venv/Scripts/python.exe -m pytest tests/ -q \ --ignore=tests/validation \ --ignore=tests/test_playwright.py \ --ignore=tests/test_integration.py \ --deselect tests/test_cache.py::test_write_only_mode ``` -------------------------------- ### finish() Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md Generates an HTML report and returns the file path. ```APIDOC ## finish() ### Description Finalizes the session, generates an HTML report, and returns the path to the report file. ``` -------------------------------- ### 打印 AI 原始响应 bbox Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 用于检查 AI 返回的原始边界框数据,确认其坐标格式。 ```python print(f"AI 原始 bbox: {response_data['bbox']}") ``` -------------------------------- ### 配置 XPath 缓存文件 Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md 定义用于元素定位的 XPath 缓存,支持在 JS 和 Python 版本间互换使用。 ```yaml # midscene_run/cache/my_task.cache.yaml midsceneVersion: 1.0.0 cacheId: my_task caches: - type: locate prompt: 登录按钮 cache: xpaths: - /html/body/div[1]/button[1] ``` -------------------------------- ### 调试失败操作 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md 通过设置 DEBUG 日志级别并启用执行记录来排查操作失败原因。 ```python from pymidscene.shared.logger import logger logger.set_level("DEBUG") agent = Agent( interface=web_page, enable_recording=True ) ``` -------------------------------- ### Execute pymidscene scripts Source: https://github.com/aipythoner/pymidscene/blob/main/docs/CLI.md Commands to run individual scripts, directories of scripts, or specific configuration files. ```bash pymidscene ./script.yaml # 跑单个脚本 pymidscene ./scripts/ # 跑目录下所有 *.yaml pymidscene --files a.yaml b.yaml # 显式多文件 pymidscene --config ./suite.yaml # 索引 yaml 的 files: 列表 ``` -------------------------------- ### WebPage Timeout Configuration Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Sets navigation and network idle timeouts for the WebPage interface. ```python web_page = WebPage( page, wait_for_navigation_timeout=5000, # 导航超时 5秒 wait_for_network_idle_timeout=10000 # 网络空闲超时 10秒 ) ``` -------------------------------- ### Caching Strategy Configuration Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Configures cache strategies for development and CI/CD environments. ```python # 开发时使用缓存 agent = Agent( interface=web_page, cache_id="dev_test", cache_strategy="read-write" ) # CI/CD 使用只读缓存 agent = Agent( interface=web_page, cache_id="ci_test", cache_strategy="read-only" ) ``` -------------------------------- ### Agent(interface, cache_id, cache_strategy) Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Initializes an Agent with specific caching configurations. The cache_strategy can be 'read-write', 'read-only', or 'write-only'. ```APIDOC ## Agent Initialization (Caching) ### Description Initializes the Agent with a specific cache ID and strategy to manage API calls and execution speed. ### Parameters - **interface** (object) - Required - The web page interface instance. - **cache_id** (string) - Required - Unique identifier for the cache file. - **cache_strategy** (string) - Required - Strategy to use: 'read-write' (default), 'read-only' (CI/CD), or 'write-only' (rebuild). ``` -------------------------------- ### Python 端验证测试结果 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 通过 evaluate 获取 JS 端的测试结果并进行断言。 ```python actual_value = await page.evaluate(f"window.testAPI.getInputValue('{element_id}')") assert actual_value == expected_value ``` -------------------------------- ### 输入框清空逻辑修复 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 在输入文本前通过模拟键盘操作清空输入框,防止内容追加。 ```python async def input_text(self, text, x=None, y=None, clear_first=True): if x is not None and y is not None: await self.page.mouse.click(x, y) await asyncio.sleep(0.1) # 清空输入框(关键修复) if clear_first: await self.page.keyboard.press("Control+a") await asyncio.sleep(0.05) await self.page.keyboard.press("Backspace") await asyncio.sleep(0.05) await self.page.keyboard.type(text) ``` -------------------------------- ### 绘制坐标对比图 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 在截图上绘制 AI 识别区域与真实区域,用于诊断坐标偏移。 ```python from PIL import Image, ImageDraw # 红色 = AI 识别区域 draw.rectangle([ai_left, ai_top, ai_right, ai_bottom], outline="red", width=3) # 绿色 = 真实区域 draw.rectangle([true_left, true_top, true_right, true_bottom], outline="lime", width=3) img.save("compare.png") ``` -------------------------------- ### ai_action(task) Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md Executes a complex task using an AI-driven plan-execute-replan loop. ```APIDOC ## ai_action(task) ### Description Performs a multi-step task by automatically planning and executing actions. ### Parameters - **task** (string) - Required - The high-level task description. ``` -------------------------------- ### Agent.ai_input(prompt, text) Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Uses AI to locate an element based on the prompt and input text into it. ```APIDOC ## Agent.ai_input(prompt, text) ### Description Locates an element on the current page using AI based on the provided prompt and performs an input action. ### Parameters - **prompt** (str) - Required - A natural language description of the target input element. - **text** (str) - Required - The text content to input into the located element. ``` -------------------------------- ### Agent.ai_click(prompt) Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Uses AI to locate an element based on the prompt and perform a click action. ```APIDOC ## Agent.ai_click(prompt) ### Description Locates an element on the current page using AI based on the provided prompt and performs a click action. ### Parameters - **prompt** (str) - Required - A natural language description of the target element to click. ``` -------------------------------- ### 异步 API 调用对比 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/PORTING_PROGRESS.md 展示了 Python 和 JavaScript 在异步执行 AI 操作时的语法差异。 ```python # Python async def main(): await agent.ai_click("按钮") ``` ```javascript // JS async function main() { await agent.aiClick("按钮"); } ``` -------------------------------- ### Verify WDA Connectivity Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/ios/README.md Use curl to verify that the WebDriverAgent server is reachable on the local machine. ```bash curl http://localhost:8100/status ``` -------------------------------- ### 通过代码配置模型 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/MODELS.md 直接在代码中设置环境变量以配置模型参数。 ```python import os os.environ["MIDSCENE_MODEL_NAME"] = "your-endpoint-id" os.environ["MIDSCENE_MODEL_API_KEY"] = "your-api-key" os.environ["MIDSCENE_MODEL_BASE_URL"] = "https://..." os.environ["MIDSCENE_MODEL_FAMILY"] = "doubao-vision" agent = PlaywrightAgent(page) ``` -------------------------------- ### 归一化坐标转像素坐标公式 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 将 0-1000 归一化坐标转换为实际像素坐标。 ```python pixel_x = round(normalized_x * width / 1000) pixel_y = round(normalized_y * height / 1000) ``` -------------------------------- ### 提高 AI 定位准确性 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md 通过提供更具体的描述字符串来优化 ai_locate 的定位效果。 ```python # 好 await agent.ai_locate("页面顶部导航栏的登录按钮") # 一般 await agent.ai_locate("登录按钮") ``` -------------------------------- ### Login Form Submission Logic Source: https://github.com/aipythoner/pymidscene/blob/main/examples/login_demo.html Handles form submission, performs basic input validation, and updates the UI status based on the result. ```javascript document.getElementById('loginForm').addEventListener('submit', function(e) { e.preventDefault(); const username = document.getElementById('username').value; const password = document.getElementById('password').value; const status = document.getElementById('status'); // 简单验证 if (!username || !password) { status.className = 'error'; status.textContent = '请输入用户名和密码!'; return; } // 模拟登录成功 // 弹窗提示 alert('登录成功!\n\n用户名: ' + username + '\n欢迎回来!'); // 页面状态更新 status.className = 'success'; status.textContent = '登录成功!欢迎 ' + username + '!'; }); ``` -------------------------------- ### 缓存格式示例 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/PORTING_PROGRESS.md 展示了与 JS 版本对齐的缓存文件格式,用于存储定位任务的 XPath 信息。 ```yaml midsceneVersion: 1.0.0 cacheId: my_task caches: - type: locate prompt: 登录按钮 cache: xpaths: - /html/body/div[1]/button[1] ``` -------------------------------- ### 自动化测试事件监听与验证逻辑 Source: https://github.com/aipythoner/pymidscene/blob/main/tests/validation/test_automation.html 包含事件记录系统、UI 交互监听器以及暴露给 Python 的测试 API。此代码段处理所有页面元素的交互反馈并记录测试结果。 ```javascript // ==================== 事件记录系统 ==================== const eventLog = document.getElementById('event-log'); const testResults = {}; function log(message, type = 'info') { const item = document.createElement('div'); item.className = `log-item ${type}`; const time = new Date().toLocaleTimeString(); item.textContent = `[${time}] ${message}`; eventLog.appendChild(item); eventLog.scrollTop = eventLog.scrollHeight; } function recordTest(testName, passed, details = '') { testResults[testName] = { passed, details, timestamp: Date.now() }; updateTestResultsUI(); } function updateTestResultsUI() { const container = document.getElementById('test-results'); container.innerHTML = ''; for (const [name, result] of Object.entries(testResults)) { const item = document.createElement('div'); item.className = 'result-item'; item.innerHTML = ` ${name} ${result.passed ? 'PASS' : 'FAIL'} ${result.details ? '- ' + result.details : ''} `; container.appendChild(item); } } // ==================== 输入事件监听 ==================== const inputElements = ['username', 'password', 'search-input', 'textarea']; inputElements.forEach(id => { const el = document.getElementById(id); el.addEventListener('focus', () => { log(`[FOCUS] ${id} 获得焦点`, 'info'); }); el.addEventListener('blur', () => { log(`[BLUR] ${id} 失去焦点`, 'info'); }); el.addEventListener('input', (e) => { log(`[INPUT] ${id} 输入内容: "${e.target.value}"`, 'success'); recordTest(`输入-${id}`, e.target.value.length > 0, `值: "${e.target.value}"`); }); el.addEventListener('change', (e) => { log(`[CHANGE] ${id} 内容变更: "${e.target.value}"`, 'success'); }); }); // ==================== 点击事件监听 ==================== const buttons = ['btn-primary', 'btn-secondary', 'btn-danger', 'btn-success', 'search-btn']; buttons.forEach(id => { const btn = document.getElementById(id); btn.addEventListener('click', (e) => { log(`[CLICK] 点击按钮: ${id} (${btn.textContent})`, 'success'); recordTest(`点击-${id}`, true); }); }); // 点击计数器 let clickCount = 0; const countDisplay = document.getElementById('click-count'); document.getElementById('btn-counter').addEventListener('click', () => { clickCount++; countDisplay.textContent = clickCount; log(`[CLICK] 计数器+1, 当前值: ${clickCount}`, 'success'); recordTest('点击-计数器', true, `计数: ${clickCount}`); }); document.getElementById('btn-reset').addEventListener('click', () => { clickCount = 0; countDisplay.textContent = 0; log(`[CLICK] 计数器重置`, 'info'); }); // ==================== Hover 事件监听 ==================== const hoverAreas = ['hover-area-1', 'hover-area-2']; hoverAreas.forEach(id => { const area = document.getElementById(id); area.addEventListener('mouseenter', () => { log(`[HOVER] 鼠标进入: ${id}`, 'success'); area.classList.add('hovered'); recordTest(`Hover-${id}`, true); }); area.addEventListener('mouseleave', () => { log(`[HOVER] 鼠标离开: ${id}`, 'info'); // 保持 hovered 状态作为验证 }); }); // ==================== 复选框/单选框监听 ==================== const checkboxes = ['checkbox-1', 'checkbox-2', 'checkbox-3']; checkboxes.forEach(id => { const cb = document.getElementById(id); cb.addEventListener('change', (e) => { log(`[CHECKBOX] ${id} ${e.target.checked ? '选中' : '取消'}: ${e.target.value}`, 'success'); recordTest(`复选框-${id}`, e.target.checked); }); }); const radios = ['radio-1', 'radio-2', 'radio-3']; radios.forEach(id => { const radio = document.getElementById(id); radio.addEventListener('change', (e) => { log(`[RADIO] 选中: ${id} (${e.target.value})`, 'success'); recordTest(`单选框-${e.target.value}`, true); }); }); // ==================== 下拉菜单监听 ==================== document.getElementById('select-menu').addEventListener('change', (e) => { log(`[SELECT] 选择: ${e.target.value}`, 'success'); recordTest('下拉菜单', e.target.value !== '', `选中: ${e.target.value}`); }); // ==================== 链接点击监听 ==================== const links = ['link-1', 'link-2', 'link-3']; links.forEach(id => { const link = document.getElementById(id); link.addEventListener('click', (e) => { e.preventDefault(); log(`[LINK] 点击链接: ${id} (${link.textContent})`, 'success'); recordTest(`链接-${id}`, true); }); }); // ==================== 清空日志 ==================== document.getElementById('clear-log').addEventListener('click', () => { eventLog.innerHTML = ''; log('日志已清空', 'info'); }); // ==================== 暴露给 Python 的验证接口 ==================== window.testAPI = { // 获取所有测试结果 getTestResults: () => testResults, // 获取指定输入框的值 getInputValue: (id) => { const el = document.getElementById(id); return el ? el.value : null; }, // 检查元素是否被点击过 wasClicked: (testName) => { return ``` -------------------------------- ### Run iOS Tests Source: https://github.com/aipythoner/pymidscene/blob/main/pymidscene/ios/README.md Execute the test suite for the iOS module using pytest. ```bash pytest tests/ios/ -v ``` -------------------------------- ### Error Handling Pattern Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Recommended pattern for checking element existence before interaction and handling exceptions. ```python try: element = await agent.ai_locate("登录按钮") if element: await agent.ai_click("登录按钮") else: print("未找到登录按钮") except Exception as e: print(f"操作失败: {e}") ``` -------------------------------- ### 加载环境变量并初始化 Agent Source: https://github.com/aipythoner/pymidscene/blob/main/docs/MODELS.md 使用 dotenv 加载配置后初始化 PlaywrightAgent。 ```python from dotenv import load_dotenv load_dotenv() agent = PlaywrightAgent(page) ``` -------------------------------- ### 减少 API 调用成本 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md 通过配置缓存 ID 和读写策略来复用已有的 AI 分析结果。 ```python agent = Agent( interface=web_page, cache_id="production", cache_strategy="read-write" ) ``` -------------------------------- ### ai_input() Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Locates an input field and enters text using an AI-driven natural language prompt. ```APIDOC ## ai_input(prompt: str, text: str) ### Description Locates an input element via AI and inputs the specified text. ### Parameters - **prompt** (str) - Required - Element description. - **text** (str) - Required - Text to input. ### Returns - **bool** - True if the input was successful, False otherwise. ``` -------------------------------- ### Define a YAML automation script Source: https://github.com/aipythoner/pymidscene/blob/main/docs/CLI.md Structure for a YAML script including platform configuration and a sequence of tasks. ```yaml web: url: https://example.com viewportWidth: 1280 output: ./result.json # 不写则落到 midscene_run/output/ tasks: - name: do something continueOnError: false flow: - aiTap: the login button - aiInput: the username field value: alice - aiKeyboardPress: Enter - aiWaitFor: the dashboard is visible timeout: 15000 # 毫秒 - aiQuery: "{ count: number }" name: stats # 结果按 name 存入 output JSON - aiAssert: the page shows the dashboard ``` -------------------------------- ### Size Type Definition Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md Defines the page size structure including dimensions and device pixel ratio. ```python class Size(TypedDict): width: float height: float dpr: Optional[float] # 设备像素比 ``` -------------------------------- ### ai_locate(description) Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md Locates an element and returns its coordinates. ```APIDOC ## ai_locate(description) ### Description Identifies the location of an element based on a natural language description. ### Parameters - **description** (string) - Required - Natural language description of the element to locate. ``` -------------------------------- ### Perform AI-driven browser actions Source: https://github.com/aipythoner/pymidscene/blob/main/README_CN.md Use natural language commands to interact with UI elements and extract structured data from web pages. ```python # 不再需要: page.click("#submit-btn-primary") await agent.ai_click("蓝色的提交按钮") # 不再需要: page.fill("input[name='email']", "test@example.com") await agent.ai_input("邮箱输入框", "test@example.com") # 使用自然语言提取结构化数据 result = await agent.ai_query({ "title": "页面标题", "price": "商品价格,数字类型" }) ``` -------------------------------- ### ai_assert 常见场景示例 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md 展示了验证页面状态、内容存在、元素状态和数量的常见断言场景。 ```python # 验证页面状态 await agent.ai_assert("页面加载完成") await agent.ai_assert("没有显示加载动画") # 验证内容存在 await agent.ai_assert("页面显示了搜索结果") await agent.ai_assert("标题中包含关键词'Python'") # 验证元素状态 await agent.ai_assert("提交按钮是可点击的") await agent.ai_assert("表单验证全部通过") # 验证数量 await agent.ai_assert("显示了至少10个商品") await agent.ai_assert("购物车中有3件商品") ``` -------------------------------- ### ai_input 示例用法 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/API.md 展示了如何输入搜索关键词、表单数据以及多行文本。 ```python # 输入搜索关键词 await agent.ai_input("搜索框", "Python 教程") # 输入用户名和密码 await agent.ai_input("用户名输入框", "admin") await agent.ai_input("密码输入框", "password123") # 输入多行文本 await agent.ai_input("备注框", "第一行\n第二行\n第三行") ``` -------------------------------- ### 提取 Markdown 中的 JSON Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 处理 AI 返回的被 markdown 代码块包裹的 JSON 响应。 ```python from ...shared.utils import safe_parse_json, extract_json_from_code_block # 先提取 JSON(处理 markdown 代码块) json_text = extract_json_from_code_block(result["content"]) response_data = safe_parse_json(json_text) ``` -------------------------------- ### JS 事件监听验证 Source: https://github.com/aipythoner/pymidscene/blob/main/docs/TROUBLESHOOTING.md 在测试页面中添加事件监听,确认输入和点击操作是否成功触发。 ```javascript element.addEventListener('input', (e) => { console.log(`输入内容: ${e.target.value}`); window.testResults[elementId] = e.target.value; }); element.addEventListener('click', () => { console.log(`点击事件触发`); window.testResults[elementId] = true; }); ```