关于 agent-browser
面向 AI Agent 的无头浏览器自动化命令行工具,借助无障碍树中的元素引用定位页面内容,并支持隔离会话、JSON 输出和 CDP 连接。
主要功能
- 01浏览器导航与交互
- 02带元素引用的无障碍快照
- 03隔离并行会话
- 04机器可读的 JSON 输出
- 05连接现有浏览器的 CDP
- 06截图和 PDF 生成
适用场景
- 01填写网页表单并导航
- 02抓取可访问的页面内容
- 03自动化测试 Web 应用
- 04并行运行浏览器任务
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ckorhonen/ claude-skills --skill agent-browser安装后在 Claude Code 中输入/agent-browser确认已加载。
详细介绍
agent-browser CLI
专为 AI Agent 打造的无头浏览器自动化 CLI,采用 Rust 实现,执行速度快,并提供针对大模型推理优化的元素引用。
概述
agent-browser 通过 CLI 提供程序化浏览器控制,专为 AI Agent 工作流打造。它使用来自无障碍树的确定性元素引用(@e1、@e2 等),适合对元素定位一致性要求较高的大模型自动化场景。
主要功能:
- 基于 Rust 的快速 CLI,并支持 Node.js 回退
- 元素引用(
@e1、@e2),便于大模型稳定推理 - 会话隔离,支持并行浏览器实例
- 提供 JSON 输出,便于程序解析
- 提供无障碍树快照,便于发现元素
- 支持通过 CDP 连接到现有浏览器实例
适用场景
- 自动化网页交互(填写表单、点击、导航)
- 通过解析无障碍树抓取网页内容
- 以编程方式测试 Web 应用
- 需要隔离浏览器会话的多 Agent 场景
- 截取屏幕截图和生成 PDF
- 监控网页状态变化
前置条件
- Node.js >= 18 或 Bun 运行时
- Chromium(通过
agent-browser install安装)
安装
# Install globally
bun install -g agent-browser
# Download Chromium
agent-browser install
# Linux with system dependencies
agent-browser install --with-deps
验证安装:
agent-browser --version
快速开始
# Navigate to a page
agent-browser open https://example.com
# Get accessibility snapshot with element refs
agent-browser snapshot -i # -i = interactive elements only
# Click an element by ref
agent-browser click @e2
# Fill a form field
agent-browser fill @e3 "[email protected]"
# Take a screenshot
agent-browser screenshot output.png
核心工作流
1. 打开页面并获取快照
# Open URL
agent-browser open https://example.com
# Get interactive elements with refs
agent-browser snapshot -i --json
快照会返回如下元素:
@e1 link "Home"
@e2 textbox "Email"
@e3 button "Submit"
2. 使用引用进行交互
# Click by ref
agent-browser click @e2
# Type into focused element
agent-browser type @e2 "[email protected]"
# Fill (clears first, then types)
agent-browser fill @e2 "[email protected]"
# Press keyboard key
agent-browser press Enter
3. 验证状态
# Check element visibility
agent-browser is visible @e3
# Get element text
agent-browser get text @e1
# Get page URL
agent-browser get url
命令参考
导航
| 命令 | 说明 |
|---|---|
open <url> | 导航到 URL |
back | 返回上一页 |
forward | 前进到下一页 |
reload | 重新加载当前页面 |
close | 关闭浏览器 |
交互
| 命令 | 说明 |
|---|---|
click <ref> | 点击元素 |
dblclick <ref> | 双击元素 |
type <ref> <text> | 在元素中输入文本 |
fill <ref> <text> | 清空元素并填入文本 |
press <key> | 按下键盘按键(Enter、Tab、Control+a) |
hover <ref> | 将鼠标悬停在元素上 |
focus <ref> | 聚焦元素 |
check <ref> | 勾选复选框 |
uncheck <ref> | 取消勾选复选框 |
select <ref> <val> | 选择下拉选项 |
scroll <dir> [px] | 滚动(上/下/左/右) |
wait <ref|ms> | 等待元素或指定毫秒数 |
信息
| 命令 | 说明 |
|---|---|
snapshot | 获取带有引用的无障碍树 |
snapshot -i | 仅显示交互元素 |
snapshot -c | 精简(移除空元素) |
snapshot -d <n> | 限制树的深度 |
get text <ref> | 获取元素文本内容 |
get html <ref> | 获取元素 HTML |
get value <ref> | 获取输入值 |
get url | 获取当前页面 URL |
get title | 获取页面标题 |
screenshot [path] | 截取屏幕截图 |
screenshot --full | 截取整页屏幕截图 |
pdf <path> | 将页面保存为 PDF |
状态检查
| 命令 | 说明 |
|---|---|
is visible <ref> | 检查元素是否可见 |
is enabled <ref> | 检查元素是否已启用 |
is checked <ref> | 检查复选框是否已勾选 |
查找元素
# Find by role and click
agent-browser find role button click --name Submit
# Find by text
agent-browser find text "Sign In" click
# Find by label
agent-browser find label "Email" fill "[email protected]"
# Find by placeholder
agent-browser find placeholder "Search..." type "query"
会话管理
会话可提供相互隔离的浏览器实例,以便并行执行:
# Use named session
agent-browser --session login-flow open https://app.com
# Different session for another task
agent-browser --session checkout open https://app.com/cart
# List active sessions
agent-browser session list
# Environment variable (persistent across commands)
export AGENT_BROWSER_SESSION=my-session
agent-browser open https://example.com
JSON 输出
使用 --json 获取机器可读的输出:
# Snapshot as JSON
agent-browser snapshot -i --json
# Get element info as JSON
agent-browser get text @e1 --json
# Parse in scripts
agent-browser get url --json | jq -r '.url'
常见问题
本节介绍常见故障及其调试方法。每个问题都包含你会看到的症状、根本原因和解决方法。
未找到浏览器
症状: Error: Browser executable not found at default path 或 agent-browser: command not found
原因: 未安装 Chromium,或者 agent-browser CLI 不在 PATH 中
解决方法:
# Install Chromium
agent-browser install
# For Linux, install system dependencies
agent-browser install --with-deps
# Verify installation
agent-browser --version
页面更改后元素引用会失效
症状: 明明刚使用过元素,却出现 Error: Element @e2 not found,或点击操作悄无声息地失败
原因: DOM 更新时(导航、页面重新加载、动态内容)元素引用会改变。引用仅对当前 DOM 快照有效。
修复:
# Always re-snapshot after major page changes
agent-browser click @e1 # Click submit
agent-browser wait 2000 # Wait for navigation
agent-browser snapshot -i --json # Get fresh refs
agent-browser click @e1 # Use new ref (was @e1 before? Verify!)
预防: 在脚本中,每次导航或动态加载后都获取新的元素引用。
会话冲突和端口绑定
症状: 出现 Error: Session "default" already in use 或 Port 9222 already in use
原因: 上一条命令或崩溃的脚本仍在运行浏览器会话,导致无法启动新会话。
修复:
# List active sessions
agent-browser session list
# Kill a specific session
agent-browser session kill my-session
# Use unique session names to avoid conflicts
agent-browser --session upload-$(date +%s) open https://app.com
# Or set environment variable once
export AGENT_BROWSER_SESSION=task-$(date +%s)
agent-browser open https://example.com
agent-browser close
无法点击或操作隐藏元素
症状: agent-browser click @e5 执行成功但没有任何反应,或元素在截图中不可见
原因: 元素位于视口之外、被 CSS 隐藏(display: none、visibility: hidden),或被其他元素遮挡。无障碍树可能会显示该元素,但浏览器无法与之交互。
修复:
# Check visibility before interaction
agent-browser is visible @e5
# Scroll to make element visible
agent-browser scroll down 500
# Take screenshot to visually verify
agent-browser screenshot current-state.png
# Try parent element if child is deeply nested
agent-browser click @e4 # Click parent button instead
预防: 在关键交互前后都截图,以确认视觉状态。
等待导航或元素超时
症状: 出现 Error: Timeout waiting for element,或点击链接后脚本无限期挂起
原因:
- 元素不存在,或出现所需的时间超过预期
- 导航卡住(网络错误、页面未加载)
- 元素选择器有误
修复:
# Explicit wait before checking for element
agent-browser wait 2000 # Wait 2 seconds
agent-browser snapshot -i --json # Check if element exists
# Wait for specific element to appear
agent-browser wait @e3
# Increase timeout with explicit waits in script
agent-browser click @submit
sleep 3 # Shell script sleep
agent-browser snapshot -i
# Check page title to verify navigation worked
agent-browser get title
预防: 在表单提交或会触发导航的链接点击后,添加明确的 wait 命令。
快照为空或缺少预期元素
症状: agent-browser snapshot -i --json 返回 [] 或只有少量元素,但截图中能看到这些元素
原因:
- 页面内容由 JavaScript(React、Vue 等)渲染,且渲染尚未完成
- 元素缺少无障碍标签或角色
-i标志的筛选条件过于严格
修复:
# Wait for content to render
agent-browser wait 2000
agent-browser snapshot -i
# Remove interactive-only filter to see all elements
agent-browser snapshot -c # Compact but includes all elements
# Increase tree depth to find nested elements
agent-browser snapshot -d 5
# Use full snapshot to diagnose
agent-browser snapshot --json | jq . | less
# Check page title to verify page loaded
agent-browser get title
预防: 打开 JavaScript 渲染量较大的页面后,添加等待延迟。
表单填充无效或文本不完整
症状: 文本似乎被截断、只输入了前几个字符,或字段仍为空
原因:
- 输入前字段未获得焦点(竞态条件)
- 字段有输入验证或字符数限制
- JavaScript 事件处理程序要求特定的输入速度或失焦事件
修复:
# Always focus explicitly before filling
agent-browser focus @e2
agent-browser wait 500 # Let field settle
agent-browser fill @e2 "[email protected]"
# For fields with slow JS event handling
agent-browser type @e2 "first part"
agent-browser wait 500
agent-browser type @e2 "second part"
# Verify what was actually entered
agent-browser get value @e2
预防: 每次填充表单后,立即使用 get value 验证输入值是否正确。
网络请求失败或外部 API 超时
症状: 页面已加载,但数据未显示;或集成测试在调用真实 API 时失败
原因:
- 外部 API 响应缓慢或无法访问
- CORS 错误(浏览器阻止对不同域的请求)
- 缺少身份验证标头
- 网络处于隔离状态(测试环境)
修复:
# Set custom headers for auth
agent-browser --headers '{"Authorization": "Bearer token123"}' open https://api.example.com
# Mock API responses instead
agent-browser network route "**/api/data" --body '{"result":"mocked"}'
# Add explicit wait for API response
agent-browser wait 3000 # Give API time to respond
agent-browser snapshot -i
# Fallback: Use `--headed` to see error messages
agent-browser --headed open https://app.com
agent-browser click @e1 # See browser console errors
预防: 测试时,使用 network route 模拟外部 API。生产环境中,运行自动化之前请确认网络连通性。
浏览器崩溃或无响应
症状: agent-browser 命令挂起,或进程因段错误而崩溃;Chrome 窗口意外关闭
原因:
- 内存不足(运行时间过长的会话或截图过多)
- CDP 连接无效
- 少见的 Chromium/Playwright 崩溃
- 系统资源不足
修复:
# Restart with fresh session
agent-browser session kill all-sessions # Or specify a name
# Use lightweight mode with limited resources
agent-browser --session lite open https://minimal-site.com
# Reduce screenshot frequency
# Instead of: agent-browser screenshot after every click
# Do: agent-browser screenshot only on failure
# Check system resources
top -n 1 | head -20
# Run with --debug for crash diagnostics
agent-browser --debug open https://example.com 2>&1 | tail -50
预防:
- 明确关闭会话:
agent-browser close - 为长时间运行的任务使用唯一的会话名称
- 在长时间运行的自动化脚本中监控内存
元素引用不明确(多个元素对应 @e1)
症状: 多个元素解析为相同的 @e 编号,点击 @e1 时操作了错误的元素
原因: 无障碍树会将相似元素(按钮、链接)分组,而 agent-browser 根据顺序分配引用,不保证唯一性
修复:
# Use full snapshot to understand structure
agent-browser snapshot -d 3 --json > structure.json
cat structure.json | jq . # Examine hierarchy
# Click using find by text if available
agent-browser find text "Specific Button Text" click
# Use CSS selector if accessibility tree isn't clear
agent-browser find selector "button.submit-btn" click
# Take screenshot and count visually
agent-browser screenshot debug.png
# Then manually map which @eN corresponds to which button
# Use context to disambiguate
agent-browser get text @e1 # Check what @e1 actually is
预防: 关键交互前,务必通过检查元素文本或截图来确认元素身份。
高级功能
CDP 连接
连接到现有的 Chrome 实例:
# Start Chrome with debugging
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
# Connect agent-browser
agent-browser --cdp 9222 snapshot
视频录制
# Start recording
agent-browser record start recording.webm https://example.com
# Perform actions...
agent-browser click @e1
agent-browser fill @e2 "test"
# Stop and save
agent-browser record stop
网络拦截
# Block requests to URL pattern
agent-browser network route "**/analytics/*" --abort
# Mock API response
agent-browser network route "**/api/user" --body '{"name": "Test"}'
# View captured requests
agent-browser network requests
自定义标头
# Set auth headers
agent-browser --headers '{"Authorization": "Bearer token123"}' open https://api.example.com
浏览器扩展
# Load extension
agent-browser --extension /path/to/extension open https://example.com
AI Agent 模式
表单自动化
#!/bin/bash
# Login automation script
agent-browser open https://app.com/login
# Get form elements
agent-browser snapshot -i --json > elements.json
# Fill credentials
agent-browser fill @e2 "[email protected]"
agent-browser fill @e3 "password123"
# Submit
agent-browser click @e4
# Wait for navigation
agent-browser wait 2000
# Verify login
agent-browser get url --json | jq -r '.url'
数据提取
#!/bin/bash
# Scrape product data
agent-browser open https://shop.com/products
# Get page content
agent-browser snapshot --json > snapshot.json
# Extract specific element text
agent-browser get text '[data-testid="price"]' --json
# Screenshot for verification
agent-browser screenshot products.png
多页面工作流
#!/bin/bash
SESSION="checkout-flow"
# Step 1: Add to cart
agent-browser --session $SESSION open https://shop.com/product/123
agent-browser --session $SESSION click @add-to-cart-button
agent-browser --session $SESSION wait 1000
# Step 2: Go to checkout
agent-browser --session $SESSION open https://shop.com/checkout
agent-browser --session $SESSION snapshot -i
# Step 3: Fill shipping
agent-browser --session $SESSION fill @shipping-name "John Doe"
agent-browser --session $SESSION fill @shipping-address "123 Main St"
# Cleanup
agent-browser --session $SESSION close
选项参考
| 选项 | 描述 |
|---|---|
--session <name> | 隔离的浏览器会话 |
--json | JSON 输出格式 |
--headed | 显示浏览器窗口(非无头模式) |
--cdp <port> | 通过 Chrome DevTools Protocol 连接 |
--headers <json> | 请求的 HTTP 标头 |
--proxy <url> | 代理服务器 |
--executable-path <path> | 自定义浏览器可执行文件 |
--extension <path> | 加载浏览器扩展 |
--full, -f | 全页截图 |
--debug | 调试输出 |
环境变量
| 变量 | 描述 |
|---|---|
AGENT_BROWSER_SESSION | 默认会话名称 |
AGENT_BROWSER_EXECUTABLE_PATH | 自定义浏览器路径 |
AGENT_BROWSER_STREAM_PORT | WebSocket 流式传输端口 |
示例
示例 1:简单网页抓取
用户请求:
"Scrape the product title and price from https://example.com/product/123"
工作流:
# 1. Navigate to page
agent-browser open https://example.com/product/123
# 2. Get accessibility snapshot
agent-browser snapshot -i --json > page.json
# 3. Identify elements (example output):
# @e5 heading "Premium Widget Pro"
# @e12 text "$49.99"
# 4. Extract data
agent-browser get text @e5 --json # Returns: {"text": "Premium Widget Pro"}
agent-browser get text @e12 --json # Returns: {"text": "$49.99"}
预期输出:
{
"title": "Premium Widget Pro",
"price": "$49.99"
}
**耗时:**2-3 秒
示例 2:提交并验证表单
用户请求:
"Fill out the contact form at https://example.com/contact and verify submission"
工作流:
# 1. Navigate and snapshot
agent-browser open https://example.com/contact
agent-browser snapshot -i
# Example snapshot output:
# @e1 textbox "Name"
# @e2 textbox "Email"
# @e3 textbox "Message"
# @e4 button "Send"
# 2. Fill form fields
agent-browser fill @e1 "John Doe"
agent-browser fill @e2 "[email protected]"
agent-browser fill @e3 "I have a question about your product"
# 3. Submit
agent-browser click @e4
# 4. Wait for response
agent-browser wait 2000
# 5. Verify success
agent-browser snapshot -i | grep "Thank you"
# Or take screenshot for manual verification
agent-browser screenshot success.png
预期结果:
- 表单提交成功
- 页面显示确认消息
- 保存显示成功状态的截图
**耗时:**4-6 秒
示例 3:使用会话的多页面工作流
用户请求:
"Add item to cart, proceed to checkout, and fill shipping info"
工作流:
# Use session for state persistence across commands
SESSION="checkout-flow-$(date +%s)"
# 1. Add to cart
agent-browser --session $SESSION open https://shop.example.com/product/widget
agent-browser --session $SESSION snapshot -i | grep "Add to Cart"
agent-browser --session $SESSION click @add-to-cart # Assuming @add-to-cart ref found
agent-browser --session $SESSION wait 1000 # Wait for cart update
# 2. Go to checkout
agent-browser --session $SESSION open https://shop.example.com/checkout
agent-browser --session $SESSION snapshot -i
# 3. Fill shipping form (refs from snapshot)
agent-browser --session $SESSION fill @shipping-name "Jane Smith"
agent-browser --session $SESSION fill @shipping-address "456 Oak Ave"
agent-browser --session $SESSION fill @shipping-city "Portland"
agent-browser --session $SESSION select @shipping-state "OR"
agent-browser --session $SESSION fill @shipping-zip "97201"
# 4. Take screenshot before submission
agent-browser --session $SESSION screenshot checkout-filled.png
# 5. Cleanup
agent-browser --session $SESSION close
预期结果:
- 商品成功加入购物车
- 填写包含配送信息的结账表单
- 保存显示已填完表单的截图
- 清理会话
**耗时:**8-12 秒
示例 4:登录并提取数据
用户请求:
"Log into dashboard, navigate to reports, and extract table data"
工作流:
SESSION="dashboard-scrape"
# 1. Login
agent-browser --session $SESSION open https://app.example.com/login
agent-browser --session $SESSION snapshot -i
# Fill login form
agent-browser --session $SESSION fill @email "[email protected]"
agent-browser --session $SESSION fill @password "secretpass"
agent-browser --session $SESSION click @submit
agent-browser --session $SESSION wait 2000
# 2. Navigate to reports
agent-browser --session $SESSION open https://app.example.com/reports
agent-browser --session $SESSION wait 1000
# 3. Extract table data
agent-browser --session $SESSION snapshot --json > reports.json
# Parse JSON to extract table rows
# @e20 table
# @e21 row "Q1 2024, $50,000, 15% growth"
# @e22 row "Q2 2024, $62,000, 24% growth"
agent-browser --session $SESSION get text @e20 --json
# 4. Cleanup
agent-browser --session $SESSION close
预期输出:
{
"reports": [
{"quarter": "Q1 2024", "revenue": "$50,000", "growth": "15%"},
{"quarter": "Q2 2024", "revenue": "$62,000", "growth": "24%"}
]
}
**耗时:**6-10 秒
故障排除
问题:未找到元素引用
症状:
Error: Element @e5 not found
**原因:**页面更新后元素 ref 发生变化,或快照已过时
解决方案:
# 1. Get fresh snapshot
agent-browser snapshot -i
# 2. Verify element ref in output
# Look for expected element in snapshot output
# 3. If element doesn't appear, try without -i flag
agent-browser snapshot # Shows all elements, not just interactive
# 4. If still missing, check if page loaded completely
agent-browser wait 2000 # Wait for page to settle
agent-browser snapshot -i
问题:等待导航超时
症状:
Error: Navigation timeout after 30000ms
**原因:**页面加载耗时过长或存在网络问题
解决方案:
# 1. Check if page is accessible
agent-browser --headed open https://example.com # Visual debugging
# 2. Increase wait time after navigation
agent-browser open https://slow-site.com
agent-browser wait 5000 # Wait 5 seconds
# 3. Check network requests
agent-browser network requests # See what's loading
# 4. Use CDP connection for better control
agent-browser --cdp 9222 open https://example.com
问题:点击无效
**症状:**元素点击命令已执行,但没有任何反应
**原因:**元素不可见、已禁用或被其他元素遮挡
解决方案:
# 1. Check if element is visible
agent-browser is visible @e3
# Returns: true/false
# 2. Check if element is enabled
agent-browser is enabled @e3
# 3. Try scrolling to element first
agent-browser scroll down 500
agent-browser wait 500
agent-browser click @e3
# 4. Take screenshot to see page state
agent-browser screenshot debug.png
# 5. Try double-click instead
agent-browser dblclick @e3
问题:表单输入未生效
**症状:**已输入文本,但表单字段仍为空
**原因:**JavaScript 框架需要特殊事件或延迟
解决方案:
# 1. Focus element first
agent-browser focus @e2
agent-browser wait 200
# 2. Use fill instead of type (clears first)
agent-browser fill @e2 "text content"
# 3. Add delays between keystrokes
agent-browser type @e2 "slow"
agent-browser wait 100
# 4. Try pressing Tab after filling to trigger validation
agent-browser fill @e2 "[email protected]"
agent-browser press Tab
问题:会话持久化问题
**症状:**无法获取之前的会话状态
**原因:**会话未正确命名,或浏览器意外关闭
解决方案:
# 1. Always use explicit session names
SESSION="my-workflow-$(date +%s)" # Unique session ID
agent-browser --session $SESSION open https://example.com
# 2. Check active sessions
agent-browser --session $SESSION get url
# If error, session doesn't exist
# 3. Don't reuse session names across runs
# Each workflow should have unique session ID
# 4. Cleanup sessions when done
agent-browser --session $SESSION close
问题:Chromium 安装失败
症状:
Error: Failed to download Chromium
**原因:**网络问题、磁盘空间不足或缺少系统依赖项
解决方案:
# 1. Check disk space
df -h # Ensure >2GB free
# 2. Retry installation with verbose output
agent-browser install --debug
# 3. On Linux, install system dependencies first
agent-browser install --with-deps
# 4. Use custom browser if needed
agent-browser --executable-path /usr/bin/chromium open https://example.com
# 5. Verify installation
agent-browser --version
ls ~/.cache/ms-playwright/ # Check if Chromium exists
问题:JSON 输出格式错误
**症状:**无法解析命令的 JSON 输出
**原因:**文本与 JSON 输出混杂,或 JSON 模式下发生错误
解决方案:
# 1. Use --json flag consistently
agent-browser get text @e5 --json # Not: agent-browser get text @e5
# 2. Redirect stderr to separate stream
agent-browser snapshot --json 2>errors.log >output.json
# 3. Validate JSON output
agent-browser snapshot --json | jq . # Will error if invalid
# 4. Check for error messages in output
agent-browser snapshot --json | grep -E '^{' | jq .
最佳实践
- 始终先获取快照:交互前先获取元素 ref
- 使用
--json进行解析:为脚本提供机器可读的输出 - 隔离会话:并行工作流使用
--session - 显式等待:导航或点击后添加
wait命令 - 交互式快照:使用
-i标志减少无关信息 - 验证状态:点击前检查元素是否可见
- 失败时截图:自动化失败时捕获当前状态