agent-browser 使用教程

项目简介

agent-browser 是 Vercel Labs 开发的专为 AI 代理设计的无头浏览器自动化 CLI 工具。它使用 Rust 编写,提供高性能的浏览器控制能力,同时保持简洁易用的命令行接口。

核心特性:

  • 🚀 高性能 Rust 实现,解析开销 < 1ms
  • 🤖 专为 AI 代理优化的命令接口
  • 🔄 支持持久化浏览器会话
  • 📸 内置截图和可访问性树提取
  • 🎯 通过引用标识符精确定位元素

GitHub: github.com/vercel-labs...


安装指南

方式 1:全局安装(推荐)

最快的使用方式,命令直接通过 Rust CLI 执行:

bash 复制代码
npm install -g agent-browser
agent-browser install  # 下载 Chromium

方式 2:快速试用(无需安装)

使用 npx 直接运行,适合临时测试:

bash 复制代码
npx agent-browser install   # 首次需要下载 Chromium
npx agent-browser open example.com

⚠️ 注意:npx 会通过 Node.js 路由,速度比全局安装慢。日常使用建议全局安装。

方式 3:项目依赖安装

在项目中固定版本:

bash 复制代码
npm install agent-browser
npx agent-browser install

package.json 中添加脚本:

json 复制代码
{
  "scripts": {
    "browser": "agent-browser"
  }
}

方式 4:Homebrew(macOS)

bash 复制代码
brew install agent-browser
agent-browser install

方式 5:从源码构建

bash 复制代码
git clone https://github.com/vercel-labs/agent-browser
cd agent-browser
pnpm install
pnpm build
pnpm build:native   # 需要安装 Rust (https://rustup.rs)
pnpm link --global
agent-browser install

Linux 系统依赖

Linux 用户需要安装系统依赖:

bash 复制代码
agent-browser install --with-deps
# 或手动安装: npx playwright install-deps chromium

快速入门

基础工作流

bash 复制代码
# 1. 打开网页
agent-browser open example.com

# 2. 获取页面结构和元素引用
agent-browser snapshot

# 3. 通过引用操作元素
agent-browser click @e2                   # 点击元素
agent-browser fill @e3 "test@example.com" # 填充表单
agent-browser get text @e1                # 获取文本

# 4. 截图
agent-browser screenshot page.png

# 5. 关闭浏览器
agent-browser close

核心命令详解

1. 导航命令

open - 打开网页

bash 复制代码
# 基础用法
agent-browser open https://example.com

# 简写(自动添加 https://)
agent-browser open example.com

# 等待特定条件
agent-browser open example.com --wait-until networkidle

选项:

  • --wait-until <state>: 等待页面状态
    • load: 等待 load 事件(默认)
    • domcontentloaded: 等待 DOM 加载
    • networkidle: 等待网络空闲

goto - 导航到新页面

bash 复制代码
agent-browser goto /about
agent-browser goto https://another-site.com

back / forward - 浏览器历史导航

bash 复制代码
agent-browser back
agent-browser forward

reload - 刷新页面

bash 复制代码
agent-browser reload
agent-browser reload --hard  # 强制刷新,清除缓存

2. 元素交互命令

snapshot - 获取页面结构

获取可访问性树(accessibility tree)和元素引用:

bash 复制代码
agent-browser snapshot

输出示例:

less 复制代码
@e1 button "Submit"
@e2 textbox "Email"
@e3 link "Learn more"
@e4 heading "Welcome"

选项:

  • --format <type>: 输出格式
    • tree: 树形结构(默认)
    • json: JSON 格式
    • flat: 扁平列表
bash 复制代码
agent-browser snapshot --format json

click - 点击元素

bash 复制代码
# 通过引用点击
agent-browser click @e2

# 通过选择器点击
agent-browser click "button.submit"
agent-browser click "#login-btn"

# 通过文本点击
agent-browser click "text=Submit"

选项:

  • --button <type>: 鼠标按钮(left, right, middle)
  • --click-count <n>: 点击次数(双击用 2)
  • --delay <ms>: 点击延迟
bash 复制代码
agent-browser click @e2 --button right
agent-browser click @e3 --click-count 2  # 双击

fill - 填充表单

bash 复制代码
# 通过引用填充
agent-browser fill @e3 "user@example.com"

# 通过选择器填充
agent-browser fill "#email" "user@example.com"
agent-browser fill "input[name='username']" "john"

选项:

  • --delay <ms>: 输入延迟(模拟真实输入)
bash 复制代码
agent-browser fill @e3 "text" --delay 100

type - 模拟键盘输入

bash 复制代码
# 逐字符输入
agent-browser type "Hello World"

# 输入特殊键
agent-browser type "Enter"
agent-browser type "Tab"
agent-browser type "Escape"

press - 按键

bash 复制代码
agent-browser press Enter
agent-browser press "Control+A"
agent-browser press "Meta+C"  # Mac: Cmd+C

select - 选择下拉选项

bash 复制代码
# 通过值选择
agent-browser select @e5 "option-value"

# 通过标签选择
agent-browser select "#country" "label=United States"

# 选择多个选项
agent-browser select @e5 "value1" "value2"

check / uncheck - 复选框操作

bash 复制代码
agent-browser check @e6
agent-browser uncheck @e6

# 通过选择器
agent-browser check "#terms"
agent-browser uncheck "input[name='newsletter']"

hover - 鼠标悬停

bash 复制代码
agent-browser hover @e7
agent-browser hover ".dropdown-menu"

3. 内容提取命令

get - 获取元素信息

bash 复制代码
# 获取文本
agent-browser get text @e1
agent-browser get text "#title"

# 获取属性
agent-browser get attribute @e2 href
agent-browser get attribute "#link" class

# 获取 HTML
agent-browser get html @e3
agent-browser get html "body"

# 获取值(表单元素)
agent-browser get value @e4
agent-browser get value "#email"

支持的属性类型:

  • text: 元素文本内容
  • html: 元素 HTML
  • value: 表单值
  • attribute <name>: 指定属性
  • property <name>: JavaScript 属性

evaluate - 执行 JavaScript

bash 复制代码
# 执行脚本并返回结果
agent-browser evaluate "document.title"
agent-browser evaluate "window.location.href"

# 复杂脚本
agent-browser evaluate "Array.from(document.querySelectorAll('a')).map(a => a.href)"

content - 获取页面内容

bash 复制代码
# 获取完整 HTML
agent-browser content

# 获取纯文本
agent-browser content --text

4. 截图和 PDF

screenshot - 截图

bash 复制代码
# 截取整个页面
agent-browser screenshot page.png

# 截取特定元素
agent-browser screenshot @e1 element.png
agent-browser screenshot "#header" header.png

# 全页面截图(包括滚动区域)
agent-browser screenshot full.png --full-page

选项:

  • --full-page: 截取完整页面
  • --quality <n>: JPEG 质量(0-100)
  • --type <format>: 图片格式(png, jpeg)
bash 复制代码
agent-browser screenshot page.jpg --type jpeg --quality 80

pdf - 生成 PDF

bash 复制代码
agent-browser pdf output.pdf

# 自定义选项
agent-browser pdf doc.pdf --format A4 --landscape

选项:

  • --format <size>: 页面大小(A4, Letter, Legal 等)
  • --landscape: 横向
  • --margin <size>: 边距

5. 等待命令

wait - 等待条件

bash 复制代码
# 等待元素出现
agent-browser wait @e1
agent-browser wait "#loading"

# 等待元素消失
agent-browser wait @e2 --state hidden

# 等待指定时间
agent-browser wait 3000  # 等待 3 秒

# 等待导航
agent-browser wait --navigation

状态选项:

  • visible: 元素可见(默认)
  • hidden: 元素隐藏
  • attached: 元素附加到 DOM
  • detached: 元素从 DOM 移除
bash 复制代码
agent-browser wait "#modal" --state visible --timeout 5000

6. 会话管理

close - 关闭浏览器

bash 复制代码
agent-browser close

clear - 清除数据

bash 复制代码
# 清除 cookies
agent-browser clear cookies

# 清除本地存储
agent-browser clear storage

# 清除所有数据
agent-browser clear all

高级用法

1. 选择器语法

agent-browser 支持多种选择器:

bash 复制代码
# CSS 选择器
agent-browser click "#submit-btn"
agent-browser click ".button.primary"

# 文本选择器
agent-browser click "text=Submit"
agent-browser click "text=/submit/i"  # 正则表达式

# 引用标识符(来自 snapshot)
agent-browser click @e1

# XPath
agent-browser click "xpath=//button[@type='submit']"

# 组合选择器
agent-browser click "button >> text=Submit"

2. 链式命令

使用 && 连接多个命令:

bash 复制代码
agent-browser open example.com && \
  agent-browser fill "#email" "user@test.com" && \
  agent-browser fill "#password" "secret" && \
  agent-browser click "#login"

3. 脚本自动化

创建 shell 脚本:

bash 复制代码
#!/bin/bash
# login.sh

agent-browser open https://example.com/login
agent-browser snapshot > elements.txt
agent-browser fill @e1 "$USERNAME"
agent-browser fill @e2 "$PASSWORD"
agent-browser click @e3
agent-browser wait "#dashboard"
agent-browser screenshot dashboard.png
agent-browser close

4. 与 AI 集成

agent-browser 设计用于 AI 代理,可以轻松集成:

javascript 复制代码
// Node.js 示例
import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);

async function aiWebAutomation(url, task) {
  // 打开页面
  await execAsync(`agent-browser open ${url}`);

  // 获取页面结构
  const { stdout } = await execAsync('agent-browser snapshot');

  // 将 snapshot 发送给 AI 分析
  const action = await analyzeWithAI(stdout, task);

  // 执行 AI 建议的操作
  await execAsync(`agent-browser ${action}`);

  // 截图验证
  await execAsync('agent-browser screenshot result.png');

  await execAsync('agent-browser close');
}

5. 调试技巧

bash 复制代码
# 启用详细日志
RUST_LOG=debug agent-browser open example.com

# 使用有头模式(显示浏览器窗口)
agent-browser open example.com --headed

# 慢速模式(便于观察)
agent-browser open example.com --slow-mo 1000

实战示例

示例 1:自动登录

bash 复制代码
#!/bin/bash
# 自动登录示例

agent-browser open https://example.com/login
agent-browser snapshot

# 填充登录表单
agent-browser fill "#username" "myuser"
agent-browser fill "#password" "mypass"

# 点击登录按钮
agent-browser click "button[type='submit']"

# 等待跳转
agent-browser wait "#dashboard" --timeout 10000

# 验证登录成功
agent-browser screenshot logged-in.png
agent-browser close

示例 2:数据抓取

bash 复制代码
#!/bin/bash
# 抓取产品信息

agent-browser open https://shop.example.com/products
agent-browser wait ".product-list"

# 获取所有产品标题
agent-browser evaluate "
  Array.from(document.querySelectorAll('.product-title'))
    .map(el => el.textContent)
" > products.json

agent-browser close

示例 3:表单自动填充

bash 复制代码
#!/bin/bash
# 批量填充表单

agent-browser open https://example.com/form
agent-browser snapshot

# 填充多个字段
agent-browser fill @e1 "John Doe"
agent-browser fill @e2 "john@example.com"
agent-browser fill @e3 "555-1234"
agent-browser select @e4 "United States"
agent-browser check @e5  # 同意条款

# 提交
agent-browser click @e6
agent-browser wait ".success-message"
agent-browser screenshot success.png
agent-browser close

示例 4:端到端测试

bash 复制代码
#!/bin/bash
# E2E 测试脚本

set -e  # 遇到错误立即退出

echo "Starting E2E test..."

# 1. 打开应用
agent-browser open http://localhost:3000
agent-browser wait "#app-ready"

# 2. 测试导航
agent-browser click "text=Products"
agent-browser wait "h1:has-text('Products')"

# 3. 测试搜索
agent-browser fill "#search" "laptop"
agent-browser press Enter
agent-browser wait ".search-results"

# 4. 验证结果
RESULTS=$(agent-browser evaluate "document.querySelectorAll('.product-item').length")
if [ "$RESULTS" -gt 0 ]; then
  echo "✓ Search test passed"
else
  echo "✗ Search test failed"
  exit 1
fi

# 5. 截图
agent-browser screenshot test-result.png

agent-browser close
echo "E2E test completed successfully!"

常见问题

Q1: 如何处理弹窗和对话框?

bash 复制代码
# 接受 alert/confirm
agent-browser evaluate "window.confirm = () => true"

# 或在打开前设置
agent-browser open example.com --accept-dialogs

Q2: 如何处理 iframe?

bash 复制代码
# 切换到 iframe
agent-browser evaluate "document.querySelector('iframe').contentWindow"

# 或使用选择器
agent-browser click "iframe >> #button-in-iframe"

Q3: 如何设置 cookies?

bash 复制代码
agent-browser evaluate "
  document.cookie = 'name=value; path=/; max-age=3600'
"

Q4: 如何模拟移动设备?

bash 复制代码
agent-browser open example.com --device "iPhone 12"

Q5: 超时错误怎么办?

bash 复制代码
# 增加超时时间
agent-browser wait @e1 --timeout 30000

# 或全局设置
export AGENT_BROWSER_TIMEOUT=30000

最佳实践

  1. 错误处理:在脚本中添加错误检查

    bash 复制代码
    if ! agent-browser click @e1; then
      echo "Click failed"
      agent-browser screenshot error.png
      exit 1
    fi
  2. 等待策略:确保元素加载完成

    bash 复制代码
    agent-browser wait @e1 --state visible
    agent-browser click @e1
  3. 截图记录:关键步骤截图便于调试

    bash 复制代码
    agent-browser screenshot step-1.png
  4. 清理资源:始终关闭浏览器

    bash 复制代码
    trap "agent-browser close" EXIT

相关资源

相关推荐
甲维斯2 小时前
完整体验一下腾讯云的CodingPlan
ai编程
chaors2 小时前
Langchain入门到精通0x02:ICEL
人工智能·langchain·ai编程
大厂码农老A4 小时前
3天实现"睡后收入"—— Cursor & Skills打造"全自动出海"Agent
人工智能·aigc·ai编程
小碗细面5 小时前
AutoClaw 澳龙上线:一键养虾时代来了,本地部署 OpenClaw 从此零门槛
人工智能·agent·ai编程
踩着两条虫5 小时前
AI 驱动的 Vue3 应用开发平台 深入探究(二):核心概念之DSL模式与数据模型
前端·vue.js·ai编程
玹外之音8 小时前
揭秘 Spring AI 文档切割:从"暴力分割"到"语义智能"的进阶之路
spring·openai·ai编程
CodeDevMaster8 小时前
从零开始:OpenClaw本地 AI 助手部署指南
人工智能·agent·ai编程
chaors9 小时前
从零学RAG0x04向量检索算法初探
人工智能·程序员·ai编程
chaors9 小时前
Langchain入门到精通0x01:结果解析器
人工智能·langchain·ai编程