历史版本与核实范围
引用固定历史提交7c429df488687f5fb955db2cd41a7989aa45efa4中的完整主指南。发布者于2026-03-17 11:50:22 UTC将项目级指南迁为应用内置技能,本页采用迁移提交中的完整主文件。参考链接按官方迁移清单指向同版本的agent-browser子目录,相关参考和模板正文未另行恢复。2026-10-18 UTC核对精确文件、Git blob及完整正文,中文为全文翻译;代码示例和原始元数据按原样保留。文档中的安装、授权、设备、清理或发布命令均为历史资料,本站未执行;当前安装与运行效果未实测。原条目仓库、名称、标识、网址、安装命令及安装量保持原值。
完整主指南
<!-- Mux 已内置 agent-browser 二进制文件,因此默认的浏览器自动化技能 必须随应用一起提供,而不是依赖外部的技能检出。 -->
使用 agent-browser 进行浏览器自动化
核心工作流
每次浏览器自动化都遵循以下模式:
- 导航:
agent-browser open <url> - 快照:
agent-browser snapshot -i(获取@e1、@e2等元素引用) - 交互:使用引用进行点击、填写、选择
- 重新快照:导航或 DOM 变化后,获取新的引用
agent-browser open https://example.com/form
agent-browser snapshot -i
# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit"
agent-browser fill @e1 "user@example.com"
agent-browser fill @e2 "password123"
agent-browser click @e3
agent-browser wait --load networkidle
agent-browser snapshot -i # Check result
命令链式调用
可以在单次 shell 调用中使用 && 将命令串联起来。浏览器通过后台守护进程在命令之间保持状态,因此链式调用是安全的,并且比分开调用更高效。
# Chain open + wait + snapshot in one call
agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i
# Chain multiple interactions
agent-browser fill @e1 "user@example.com" && agent-browser fill @e2 "password123" && agent-browser click @e3
# Navigate and capture
agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser screenshot page.png
何时链式调用: 当你在继续之前不需要读取中间命令的输出时(例如 open + wait + screenshot),使用 &&。当你需要先解析输出时(例如先快照以发现引用,然后使用这些引用进行交互),应分开运行命令。
处理身份验证
在自动化需要登录的网站时,选择适合的方法:
选项 1:从用户浏览器导入认证(一次性任务最快)
# Connect to the user's running Chrome (they're already logged in)
agent-browser --auto-connect state save ./auth.json
# Use that auth state
agent-browser --state ./auth.json open https://app.example.com/dashboard
状态文件以明文形式包含会话令牌——请添加到 .gitignore,并在不再需要时删除。设置 AGENT_BROWSER_ENCRYPTION_KEY 以实现静态加密。
选项 2:持久化配置文件(重复性任务最简单)
# First run: login manually or via automation
agent-browser --profile ~/.myapp open https://app.example.com/login
# ... fill credentials, submit ...
# All future runs: already authenticated
agent-browser --profile ~/.myapp open https://app.example.com/dashboard
选项 3:会话名称(自动保存/恢复 cookie 和 localStorage)
agent-browser --session-name myapp open https://app.example.com/login
# ... login flow ...
agent-browser close # State auto-saved
# Next time: state auto-restored
agent-browser --session-name myapp open https://app.example.com/dashboard
选项 4:认证保险库(凭据加密存储,按名称登录)
echo "$PASSWORD" | agent-browser auth save myapp --url https://app.example.com/login --username user --password-stdin
agent-browser auth login myapp
选项 5:状态文件(手动保存/加载)
# After logging in:
agent-browser state save ./auth.json
# In a future session:
agent-browser state load ./auth.json
agent-browser open https://app.example.com/dashboard
有关 OAuth、2FA、基于 cookie 的认证以及令牌刷新模式,请参阅 references/authentication.md。
基本命令
# Navigation
agent-browser open <url> # Navigate (aliases: goto, navigate)
agent-browser close # Close browser
# Snapshot
agent-browser snapshot -i # Interactive elements with refs (recommended)
agent-browser snapshot -i -C # Include cursor-interactive elements (divs with onclick, cursor:pointer)
agent-browser snapshot -s "#selector" # Scope to CSS selector
# Interaction (use @refs from snapshot)
agent-browser click @e1 # Click element
agent-browser click @e1 --new-tab # Click and open in new tab
agent-browser fill @e2 "text" # Clear and type text
agent-browser type @e2 "text" # Type without clearing
agent-browser select @e1 "option" # Select dropdown option
agent-browser check @e1 # Check checkbox
agent-browser press Enter # Press key
agent-browser keyboard type "text" # Type at current focus (no selector)
agent-browser keyboard inserttext "text" # Insert without key events
agent-browser scroll down 500 # Scroll page
agent-browser scroll down 500 --selector "div.content" # Scroll within a specific container
# Get information
agent-browser get text @e1 # Get element text
agent-browser get url # Get current URL
agent-browser get title # Get page title
# Wait
agent-browser wait @e1 # Wait for element
agent-browser wait --load networkidle # Wait for network idle
agent-browser wait --url "**/page" # Wait for URL pattern
agent-browser wait 2000 # Wait milliseconds
# Downloads
agent-browser download @e1 ./file.pdf # Click element to trigger download
agent-browser wait --download ./output.zip # Wait for any download to complete
agent-browser --download-path ./downloads open <url> # Set default download directory
# Viewport & Device Emulation
agent-browser set viewport 1920 1080 # Set viewport size (default: 1280x720)
agent-browser set viewport 1920 1080 2 # 2x retina (same CSS size, higher res screenshots)
agent-browser set device "iPhone 14" # Emulate device (viewport + user agent)
# Capture
agent-browser screenshot # Screenshot to temp dir
agent-browser screenshot --full # Full page screenshot
agent-browser screenshot --annotate # Annotated screenshot with numbered element labels
agent-browser pdf output.pdf # Save as PDF
# Diff (compare page states)
agent-browser diff snapshot # Compare current vs last snapshot
agent-browser diff snapshot --baseline before.txt # Compare current vs saved file
agent-browser diff screenshot --baseline before.png # Visual pixel diff
agent-browser diff url <url1> <url2> # Compare two pages
agent-browser diff url <url1> <url2> --wait-until networkidle # Custom wait strategy
agent-browser diff url <url1> <url2> --selector "#main" # Scope to element
常见模式
表单提交
agent-browser open https://example.com/signup
agent-browser snapshot -i
agent-browser fill @e1 "Jane Doe"
agent-browser fill @e2 "jane@example.com"
agent-browser select @e3 "California"
agent-browser check @e4
agent-browser click @e5
agent-browser wait --load networkidle
使用认证保险库进行身份验证(推荐)
# Save credentials once (encrypted with AGENT_BROWSER_ENCRYPTION_KEY)
# Recommended: pipe password via stdin to avoid shell history exposure
echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
# Login using saved profile (LLM never sees password)
agent-browser auth login github
# List/show/delete profiles
agent-browser auth list
agent-browser auth show github
agent-browser auth delete github
使用状态持久化进行身份验证
# Login once and save state
agent-browser open https://app.example.com/login
agent-browser snapshot -i
agent-browser fill @e1 "$USERNAME"
agent-browser fill @e2 "$PASSWORD"
agent-browser click @e3
agent-browser wait --url "**/dashboard"
agent-browser state save auth.json
# Reuse in future sessions
agent-browser state load auth.json
agent-browser open https://app.example.com/dashboard
会话持久化
# Auto-save/restore cookies and localStorage across browser restarts
agent-browser --session-name myapp open https://app.example.com/login
# ... login flow ...
agent-browser close # State auto-saved to ~/.agent-browser/sessions/
# Next time, state is auto-loaded
agent-browser --session-name myapp open https://app.example.com/dashboard
# Encrypt state at rest
export AGENT_BROWSER_ENCRYPTION_KEY=$(openssl rand -hex 32)
agent-browser --session-name secure open https://app.example.com
# Manage saved states
agent-browser state list
agent-browser state show myapp-default.json
agent-browser state clear myapp
agent-browser state clean --older-than 7
数据提取
agent-browser open https://example.com/products
agent-browser snapshot -i
agent-browser get text @e5 # Get specific element text
agent-browser get text body > page.txt # Get all page text
# JSON output for parsing
agent-browser snapshot -i --json
agent-browser get text @e1 --json
并行会话
agent-browser --session site1 open https://site-a.com
agent-browser --session site2 open https://site-b.com
agent-browser --session site1 snapshot -i
agent-browser --session site2 snapshot -i
agent-browser session list
连接到现有 Chrome
# Auto-discover running Chrome with remote debugging enabled
agent-browser --auto-connect open https://example.com
agent-browser --auto-connect snapshot
# Or with explicit CDP port
agent-browser --cdp 9222 snapshot
配色方案(深色模式)
# Persistent dark mode via flag (applies to all pages and new tabs)
agent-browser --color-scheme dark open https://example.com
# Or via environment variable
AGENT_BROWSER_COLOR_SCHEME=dark agent-browser open https://example.com
# Or set during session (persists for subsequent commands)
agent-browser set media dark
视口与响应式测试
# Set a custom viewport size (default is 1280x720)
agent-browser set viewport 1920 1080
agent-browser screenshot desktop.png
# Test mobile-width layout
agent-browser set viewport 375 812
agent-browser screenshot mobile.png
# Retina/HiDPI: same CSS layout at 2x pixel density
# Screenshots stay at logical viewport size, but content renders at higher DPI
agent-browser set viewport 1920 1080 2
agent-browser screenshot retina.png
# Device emulation (sets viewport + user agent in one step)
agent-browser set device "iPhone 14"
agent-browser screenshot device.png
scale 参数(第 3 个参数)在不改变 CSS 布局的情况下设置 window.devicePixelRatio。在测试视网膜渲染或捕获更高分辨率截图时使用它。
可视化浏览器(调试)
agent-browser --headed open https://example.com
agent-browser highlight @e1 # Highlight element
agent-browser record start demo.webm # Record session
agent-browser profiler start # Start Chrome DevTools profiling
agent-browser profiler stop trace.json # Stop and save profile (path optional)
使用 AGENT_BROWSER_HEADED=1 通过环境变量启用有头模式。浏览器扩展在有头和无头模式下均可使用。
本地文件(PDF、HTML)
# Open local files with file:// URLs
agent-browser --allow-file-access open file:///path/to/document.pdf
agent-browser --allow-file-access open file:///path/to/page.html
agent-browser screenshot output.png
iOS 模拟器(移动版 Safari)
# List available iOS simulators
agent-browser device list
# Launch Safari on a specific device
agent-browser -p ios --device "iPhone 16 Pro" open https://example.com
# Same workflow as desktop - snapshot, interact, re-snapshot
agent-browser -p ios snapshot -i
agent-browser -p ios tap @e1 # Tap (alias for click)
agent-browser -p ios fill @e2 "text"
agent-browser -p ios swipe up # Mobile-specific gesture
# Take screenshot
agent-browser -p ios screenshot mobile.png
# Close session (shuts down simulator)
agent-browser -p ios close
要求: 装有 Xcode 的 macOS、Appium(npm install -g appium && appium driver install xcuitest)
真实设备: 如果预先配置,可与物理 iOS 设备配合使用。使用 --device "<UDID>",其中 UDID 来自 xcrun xctrace list devices。
安全
所有安全功能均为可选项。默认情况下,agent-browser 对导航、操作或输出不施加任何限制。
内容边界(推荐用于 AI 代理)
启用 --content-boundaries 将页面来源的输出包裹在标记中,帮助 LLM 区分工具输出与不受信任的页面内容:
export AGENT_BROWSER_CONTENT_BOUNDARIES=1
agent-browser snapshot
# Output:
# --- AGENT_BROWSER_PAGE_CONTENT nonce=<hex> origin=https://example.com ---
# [accessibility tree]
# --- END_AGENT_BROWSER_PAGE_CONTENT nonce=<hex> ---
域名允许列表
将导航限制为受信任的域名。*.example.com 之类的通配符也会匹配裸域名 example.com。对非允许域名的子资源请求、WebSocket 和 EventSource 连接也会被阻止。请包含目标页面依赖的 CDN 域名:
export AGENT_BROWSER_ALLOWED_DOMAINS="example.com,*.example.com"
agent-browser open https://example.com # OK
agent-browser open https://malicious.com # Blocked
操作策略
使用策略文件来控制破坏性操作:
export AGENT_BROWSER_ACTION_POLICY=./policy.json
示例 policy.json:
{ "default": "deny", "allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"] }
认证保险库操作(auth login 等)绕过操作策略,但域名允许列表仍然适用。
输出限制
防止大页面造成上下文泛滥:
export AGENT_BROWSER_MAX_OUTPUT=50000
差异比较(验证更改)
在执行操作后使用 diff snapshot 验证其是否产生了预期效果。它会将会话中当前的辅助功能树与上次快照进行比较。
# Typical workflow: snapshot -> action -> diff
agent-browser snapshot -i # Take baseline snapshot
agent-browser click @e2 # Perform action
agent-browser diff snapshot # See what changed (auto-compares to last snapshot)
对于视觉回归测试或监控:
# Save a baseline screenshot, then compare later
agent-browser screenshot baseline.png
# ... time passes or changes are made ...
agent-browser diff screenshot --baseline baseline.png
# Compare staging vs production
agent-browser diff url https://staging.example.com https://prod.example.com --screenshot
diff snapshot 输出使用 + 表示新增,- 表示移除,类似于 git diff。diff screenshot 会生成一张差异图像,变更的像素以红色高亮显示,并附带不匹配百分比。
超时与缓慢页面
本地浏览器的默认 Playwright 超时为 25 秒。可以通过 AGENT_BROWSER_DEFAULT_TIMEOUT 环境变量(值为毫秒)覆盖。对于缓慢的网站或大页面,应使用显式等待而非依赖默认超时:
# Wait for network activity to settle (best for slow pages)
agent-browser wait --load networkidle
# Wait for a specific element to appear
agent-browser wait "#content"
agent-browser wait @e1
# Wait for a specific URL pattern (useful after redirects)
agent-browser wait --url "**/dashboard"
# Wait for a JavaScript condition
agent-browser wait --fn "document.readyState === 'complete'"
# Wait a fixed duration (milliseconds) as a last resort
agent-browser wait 5000
当处理持续缓慢的网站时,在 open 之后使用 wait --load networkidle 确保页面在截图之前完全加载。如果特定元素渲染缓慢,直接使用 wait <selector> 或 wait @ref 等待它。
会话管理与清理
在同时运行多个代理或自动化时,始终使用命名会话来避免冲突:
# Each agent gets its own isolated session
agent-browser --session agent1 open site-a.com
agent-browser --session agent2 open site-b.com
# Check active sessions
agent-browser session list
完成后始终关闭浏览器会话以避免泄漏进程:
agent-browser close # Close default session
agent-browser --session agent1 close # Close specific session
如果之前的会话没有正确关闭,守护进程可能仍在运行。在开始新工作之前使用 agent-browser close 清理它。
引用生命周期(重要)
引用(@e1、@e2 等)在页面变化时会失效。始终在以下情况后重新快照:
- 点击导航的链接或按钮
- 表单提交
- 动态内容加载(下拉菜单、模态框)
agent-browser click @e5 # Navigates to new page
agent-browser snapshot -i # MUST re-snapshot
agent-browser click @e1 # Use new refs
标注截图(视觉模式)
使用 --annotate 获取在交互元素上叠加编号标签的截图。每个标签 [N] 对应引用 @eN。这也会缓存引用,因此你可以立即与元素交互而无需单独快照。
在原生模式下,这目前适用于基于 CDP 的浏览器路径(Chromium/Lightpanda)。Safari/WebDriver 后端尚不支持 --annotate。
agent-browser screenshot --annotate
# Output includes the image path and a legend:
# [1] @e1 button "Submit"
# [2] @e2 link "Home"
# [3] @e3 textbox "Email"
agent-browser click @e2 # Click using ref from annotated screenshot
在以下情况下使用标注截图:
- 页面有无标签的图标按钮或仅视觉元素
- 你需要验证视觉布局或样式
- 存在 Canvas 或图表元素(文本快照不可见)
- 你需要关于元素位置的空间推理
语义定位器(引用的替代方案)
当引用不可用或不可靠时,使用语义定位器:
agent-browser find text "Sign In" click
agent-browser find label "Email" fill "user@test.com"
agent-browser find role button click --name "Submit"
agent-browser find placeholder "Search" type "query"
agent-browser find testid "submit-btn" click
JavaScript 求值(eval)
使用 eval 在浏览器上下文中运行 JavaScript。Shell 引用可能会破坏复杂表达式——使用 --stdin 或 -b 来避免问题。
# Simple expressions work with regular quoting
agent-browser eval 'document.title'
agent-browser eval 'document.querySelectorAll("img").length'
# Complex JS: use --stdin with heredoc (RECOMMENDED)
agent-browser eval --stdin <<'EVALEOF'
JSON.stringify(
Array.from(document.querySelectorAll("img"))
.filter(i => !i.alt)
.map(i => ({ src: i.src.split("/").pop(), width: i.width }))
)
EVALEOF
# Alternative: base64 encoding (avoids all shell escaping issues)
agent-browser eval -b "$(echo -n 'Array.from(document.querySelectorAll("a")).map(a => a.href)' | base64)"
为什么这很重要: 当 shell 处理你的命令时,内部双引号、! 字符(历史展开)、反引号和 $() 都可能在 JavaScript 到达 agent-browser 之前破坏它。--stdin 和 -b 标志完全绕过 shell 解释。
经验法则:
- 单行、无嵌套引号 -> 使用单引号的常规
eval 'expression'即可 - 嵌套引号、箭头函数、模板字面量或多行 -> 使用
eval --stdin <<'EVALEOF' - 程序化/生成的脚本 -> 使用带 base64 的
eval -b
配置文件
在项目根目录创建 agent-browser.json 以保存持久设置:
{
"headed": true,
"proxy": "http://localhost:8080",
"profile": "./browser-data"
}
优先级(从低到高):~/.agent-browser/config.json < ./agent-browser.json < 环境变量 < CLI 标志。使用 --config <path> 或 AGENT_BROWSER_CONFIG 环境变量指定自定义配置文件(如果缺失/无效则报错退出)。所有 CLI 选项映射到 camelCase 键(例如 --executable-path -> "executablePath")。布尔标志接受 true/false 值(例如 --headed false 覆盖配置)。用户配置和项目配置中的扩展会合并,而非替换。
深入文档
| 参考 | 使用场景 |
|---|---|
| references/commands.md | 包含所有选项的完整命令参考 |
| references/snapshot-refs.md | 引用生命周期、失效规则、故障排除 |
| references/session-management.md | 并行会话、状态持久化、并发抓取 |
| references/authentication.md | 登录流程、OAuth、2FA 处理、状态复用 |
| references/video-recording.md | 用于调试和文档的记录工作流 |
| references/profiling.md | 用于性能分析的 Chrome DevTools 性能分析 |
| references/proxy-support.md | 代理配置、地理位置测试、轮换代理 |
实验性:原生模式
agent-browser 有一个实验性的原生 Rust 守护进程,它通过 CDP 直接与 Chrome 通信,完全绕过 Node.js 和 Playwright。它是可选的,目前尚不建议用于生产环境。
# Enable via flag
agent-browser --native open example.com
# Enable via environment variable (avoids passing --native every time)
export AGENT_BROWSER_NATIVE=1
agent-browser open example.com
原生守护进程支持 Chromium 和 Safari(通过 WebDriver)。Firefox 和 WebKit 尚不支持。所有核心命令(navigate、snapshot、click、fill、screenshot、cookies、storage、tabs、eval 等)在原生模式下行为一致。在同一会话中切换原生模式和默认模式之前,使用 agent-browser close。
浏览器引擎选择
使用 --engine 选择本地浏览器引擎。默认是 chrome。
# Use Lightpanda (fast headless browser, requires separate install)
agent-browser --engine lightpanda open example.com
# Via environment variable
export AGENT_BROWSER_ENGINE=lightpanda
agent-browser open example.com
# With custom binary path
agent-browser --engine lightpanda --executable-path /path/to/lightpanda open example.com
支持的引擎:
chrome(默认)——通过 CDP 的 Chrome/Chromiumlightpanda——通过 CDP 的 Lightpanda 无头浏览器(比 Chrome 快 10 倍,内存少 10 倍)
Lightpanda 不支持 --extension、--profile、--state 或 --allow-file-access。从 https://lightpanda.io/docs/open-source/installation 安装 Lightpanda。
即用型模板
| 模板 | 描述 |
|---|---|
| templates/form-automation.sh | 带验证的表单填写 |
| templates/authenticated-session.sh | 登录一次,复用状态 |
| templates/capture-workflow.sh | 带截图的内容提取 |
./templates/form-automation.sh https://example.com/form
./templates/authenticated-session.sh https://app.example.com/login
./templates/capture-workflow.sh https://example.com ./output
原始元数据
name: agent-browser
description: Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction.
allowed-tools: Bash(npx agent-browser:*), Bash(agent-browser:*)