mcpField
A
agent-browser

agent-browser

github.com/jezwebAgent 工作流1.1k469 次安装3 周前更新
代码仓库

关于 agent-browser

agent-browser 是用于浏览器自动化的命令行工具,供 Agent 通过页面快照、元素引用和语义定位来操作网页。它还支持会话管理、数据提取、截图比较及可选的导航和操作限制。

主要功能

  1. 01导航、快照及页面交互
  2. 02表单填写与数据提取
  3. 03会话状态保存和并行会话
  4. 04连接现有 Chrome
  5. 05截图与页面差异比较
  6. 06域名白名单和操作策略

适用场景

  1. 01自动填写并提交网页表单
  2. 02跨页面提取文本或结构化信息
  3. 03验证页面操作前后的变化
  4. 04隔离并管理多个浏览器自动化会话

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jezweb/claude-skills --skill agent-browser

安装后在 Claude Code 中输入/agent-browser确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
authentication.md
commands.md
profiling.md
proxy-support.md
session-management.md
snapshot-refs.md
video-recording.md
templates/
authenticated-session.sh
capture-workflow.sh
form-automation.sh

详细介绍

使用 agent-browser 进行浏览器自动化

核心工作流

每次浏览器自动化都遵循以下模式:

  1. 导航:agent-browser open <url>
  2. 快照:agent-browser snapshot -i(获取 @e1、@e2 等元素引用)
  3. 交互:使用引用进行点击、填写和选择
  4. 重新获取快照:导航或 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 "[email protected]"
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 "[email protected]" && 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

**何时串联:**如果不需要读取中间命令的输出再继续操作(例如,打开页面 + 等待 + 截图),请使用 &&。如果需要先解析输出(例如,先获取快照以发现引用,再使用这些引用进行交互),则应分开运行命令。

基本命令

# 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

# 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 "[email protected]"
agent-browser select @e3 "California"
agent-browser check @e4
agent-browser click @e5
agent-browser wait --load networkidle
使用 Auth Vault 进行身份验证(推荐)
# 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
可视化浏览器(调试)
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)
本地文件(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

**要求:**macOS、Xcode 和 Appium(npm install -g appium && appium driver install xcuitest)

**真机:**预先配置后,也可使用实体 iOS 设备。使用 --device "<UDID>",其中 UDID 来自 xcrun xctrace list devices。

安全

所有安全功能均需选择启用。默认情况下,agent-browser 不会限制导航、操作或输出。

内容边界(推荐用于 AI Agent)

启用 --content-boundaries,将页面来源的输出用标记括起来,帮助大模型区分工具输出和不可信的页面内容:

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 Vault 操作(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 等待该元素。

会话管理与清理

同时运行多个 Agent 或自动化任务时,请始终使用命名会话,以避免冲突:

# 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 清理。

Ref 生命周期(重要)

页面发生变化时,Ref(@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] 都对应 Ref @eN。此操作还会缓存 Ref,因此你无需单独创建快照,即可立即与元素交互。

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

以下情况请使用带注释的屏幕截图:

  • 页面上有未标记的图标按钮或仅有视觉呈现的元素
  • 需要确认视觉布局或样式
  • 页面中有画布或图表元素(文本快照无法捕获)
  • 需要根据元素位置进行空间推理

语义定位器(Ref 的替代方案)

Ref 不可用或不可靠时,请使用语义定位器:

agent-browser find text "Sign In" click
agent-browser find label "Email" fill "[email protected]"
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'
  • 程序生成的脚本 -> 使用 eval -b 和 base64

配置文件

在项目根目录中创建 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.mdRef 生命周期、失效规则和故障排除
references/session-management.md并行会话、状态持久化和并发抓取
references/authentication.md登录流程、OAuth、双重身份验证处理和状态复用
references/video-recording.md用于调试和编写文档的录制工作流
references/profiling.md用于性能分析的 Chrome DevTools 性能分析
references/proxy-support.md代理配置、地理位置测试和轮换代理

即用模板

模板描述
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

评论

支持 Markdown