100 个 Agent Skills 盘点(三):浏览器自动化与爬虫

2845 字
14 分钟
100 个 Agent Skills 盘点(三):浏览器自动化与爬虫

封面
封面

写在前面#

这是「100 个 Agent Skills 盘点」系列的第三篇。如果说数据库 Skills 让 Agent 能”读写数据”,那浏览器 Skills 尙让 Agent 能”看见世界”——打开网页、点击按钮、填写表单、截取截图、抓取数据。

浏览器自动化 = Agent 的”眼睛和手”。


1. Puppeteer MCP Server 🎭#

类别: 浏览器自动化 协议: MCP

Puppeteer 是 Google 官方维护的无头浏览器控制库。它通过 DevTools Protocol 直接控制 Chrome,性能优异,API 简洁。

能力说明:

  • 页面导航和截图
  • 表单填写和按钮点击
  • PDF 生成
  • 网络请求拦截
  • 性能分析

Agent 使用场景:

// Agent 自动化测试登录流程
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com/login');
await page.type('#email', 'user@example.com');
await page.type('#password', 'password123');
await page.click('#login-btn');
await page.waitForNavigation();
// 截图记录结果
await page.screenshot({ path: 'login-result.png', fullPage: true });
// 检查是否登录成功
const isLoggedIn = await page.$('.user-dashboard') !== null;
console.log('Login success:', isLoggedIn);

典型指令:

用 Puppeteer 打开我们的登录页面,测试以下场景:
1. 正确的邮箱和密码 → 应该跳转到 dashboard
2. 错误的密码 → 应该显示错误提示
3. 空的邮箱 → 应该显示验证错误
每个场景截图保存。

2. Playwright MCP Server 🎪#

类别: 跨浏览器自动化 协议: MCP

Playwright 是微软出品的下一代浏览器自动化工具,支持 Chrome、Firefox、Safari 三大引擎,API 现代化,功能更强大。

能力说明:

  • 跨浏览器测试(Chromium / Firefox / WebKit)
  • 自动等待元素(告别 sleep)
  • 网络请求拦截和模拟
  • 移动端模拟
  • 代码生成(Codegen)

Agent 使用场景:

# Agent 测试响应式设计
from playwright.async_api import async_playwright
async with async_playwright() as p:
browser = await p.chromium.launch()
# 测试不同设备尺寸
devices = [
{'width': 375, 'height': 812, 'name': 'iPhone'},
{'width': 768, 'height': 1024, 'name': 'iPad'},
{'width': 1920, 'height': 1080, 'name': 'Desktop'}
]
for device in devices:
page = await browser.new_page(
viewport={'width': device['width'], 'height': device['height']}
)
await page.goto('https://example.com')
await page.screenshot(path=f"screenshot-{device['name']}.png")
await page.close()

典型指令:

用 Playwright 测试我们网站在 iPhone、iPad 和桌面端的
显示效果,截图对比,检查是否有布局问题。

Puppeteer vs Playwright:

特性PuppeteerPlaywright
浏览器支持Chrome/FirefoxChrome/Firefox/Safari
维护方GoogleMicrosoft
自动等待需手动配置内置
代码生成❌✅ Codegen
并行测试一般优秀
社区生态极丰富快速成长

3. Selenium MCP Server 🌐#

类别: 经典浏览器自动化 协议: MCP

Selenium 是浏览器自动化的”老前辈”,虽然不如 Puppeteer/Playwright 现代,但在企业环境中仍然广泛使用。

能力说明:

  • WebDriver 协议控制浏览器
  • 支持几乎所有编程语言
  • 企业级测试框架集成
  • Grid 分布式测试

Agent 使用场景:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://example.com")
# 等待元素出现并交互
wait = WebDriverWait(driver, 10)
search_box = wait.until(
EC.presence_of_element_located((By.NAME, "q"))
)
search_box.send_keys("AI agent skills")
search_box.submit()

典型指令:

用 Selenium 编写一个自动化脚本,
每天早上 9 点检查我们产品的首页是否正常加载,
如果加载失败则发送告警。

4. 网页抓取 (Web Scraping) 🕸️#

类别: 数据采集 适用工具: Cheerio / BeautifulSoup / Scrapy

网页抓取是从网站提取结构化数据的核心能力。Agent 可以用它收集竞品信息、监控价格、聚合新闻。

能力说明:

  • HTML 解析和数据提取
  • CSS 选择器 / XPath 定位
  • 反爬虫策略处理
  • 数据清洗和结构化

Agent 使用场景:

// Agent 抓取技术博客文章列表
const cheerio = require('cheerio');
const response = await fetch('https://tech-blog.example.com');
const html = await response.text();
const $ = cheerio.load(html);
const articles = [];
$('.post-card').each((i, el) => {
articles.push({
title: $(el).find('h2').text().trim(),
url: $(el).find('a').attr('href'),
summary: $(el).find('.summary').text().trim(),
date: $(el).find('.date').text().trim()
});
});
console.log(`Found ${articles.length} articles`);

典型指令:

抓取 Hacker News 首页的前 30 条新闻,
提取标题、链接、分数和评论数,
按分数排序后输出为 JSON。

常用抓取工具对比:

工具语言特点适用场景
CheerioJS快速、轻量静态页面
BeautifulSoupPython简单易用快速原型
ScrapyPython全功能框架大规模采集
PuppeteerJS渲染页面动态页面

5. 截图与视觉记录 📸#

类别: 视觉自动化 适用工具: Puppeteer / Playwright

截图能力让 Agent 能”看到”页面的样子,用于测试验证、Bug 记录、设计对比。

能力说明:

  • 全页面截图
  • 元素级截图
  • 不同设备尺寸截图
  • 对比截图(before/after)

Agent 使用场景:

// Agent 做视觉回归测试
const puppeteer = require('puppeteer');
const pixelmatch = require('pixelmatch');
const { PNG } = require('pngjs');
const fs = require('fs');
async function visualRegression(url, baselinePath, currentPath) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto(url, { waitUntil: 'networkidle0' });
await page.screenshot({ path: currentPath, fullPage: true });
// 对比基线图
const baseline = PNG.sync.read(fs.readFileSync(baselinePath));
const current = PNG.sync.read(fs.readFileSync(currentPath));
const diff = new PNG({ width: baseline.width, height: baseline.height });
const mismatch = pixelmatch(
baseline.data, current.data, diff.data,
baseline.width, baseline.height,
{ threshold: 0.1 }
);
console.log(`Pixel mismatch: ${mismatch} (${(mismatch / (baseline.width * baseline.height) * 100).toFixed(2)}%)`);
return mismatch;
}

典型指令:

对网站的首页、产品页、登录页分别截图,
保存为基线图,以后每次部署后自动对比,
差异超过 1% 则告警。

6. PDF 生成与处理 📄#

类别: 文档生成 适用工具: Puppeteer / PDFKit / jsPDF

Agent 可以将网页转换为 PDF,或生成结构化的 PDF 文档——报告、发票、简历等。

能力说明:

  • 网页转 PDF
  • 动态数据填充模板
  • PDF 合并和拆分
  • 添加水印和签名

Agent 使用场景:

// Agent 生成月度报告 PDF
const puppeteer = require('puppeteer');
async function generateReport(data) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// 用 HTML 模板渲染报告
const html = `
<html>
<head>
<style>
body { font-family: 'Noto Sans SC', sans-serif; padding: 40px; }
.header { text-align: center; border-bottom: 2px solid #333; padding-bottom: 20px; }
.metric { display: inline-block; width: 30%; text-align: center; margin: 20px 1%; }
.metric .value { font-size: 48px; font-weight: bold; color: #2563eb; }
.metric .label { font-size: 14px; color: #666; }
table { width: 100%; border-collapse: collapse; margin-top: 30px; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background: #f5f5f5; }
</style>
</head>
<body>
<div class="header">
<h1>月度运营报告 - ${data.month}</h1>
</div>
<div class="metric"><div class="value">${data.users}</div><div class="label">活跃用户</div></div>
<div class="metric"><div class="value">${data.revenue}</div><div class="label">收入(万元)</div></div>
<div class="metric"><div class="value">${data.growth}%</div><div class="label">增长率</div></div>
<table>
<tr><th>指标</th><th>本月</th><th>上月</th><th>变化</th></tr>
${data.details.map(d => `<tr><td>${d.name}</td><td>${d.current}</td><td>${d.previous}</td><td>${d.change}</td></tr>`).join('')}
</table>
</body>
</html>
`;
await page.setContent(html, { waitUntil: 'networkidle0' });
await page.pdf({
path: `report-${data.month}.pdf`,
format: 'A4',
printBackground: true
});
}

典型指令:

根据这个月的运营数据生成一份 PDF 报告,
包含关键指标卡片、趋势图表和详细数据表格。

7. 表单自动填写 📝#

类别: 表单自动化 适用工具: Puppeteer / Playwright

表单填写是重复性最高的工作之一。Agent 可以自动填写注册表单、申请表、调查问卷等。

能力说明:

  • 自动识别表单字段
  • 根据数据源自动填充
  • 处理下拉框、复选框、日期选择器
  • 文件上传

Agent 使用场景:

// Agent 批量填写申请表
async function fillApplication(page, userData) {
// 基本信息
await page.fill('#firstName', userData.firstName);
await page.fill('#lastName', userData.lastName);
await page.fill('#email', userData.email);
await page.fill('#phone', userData.phone);
// 下拉框选择
await page.selectOption('#country', userData.country);
await page.selectOption('#education', userData.education);
// 日期选择
await page.fill('#birthDate', userData.birthDate);
// 文件上传
await page.setInputFiles('#resume', userData.resumePath);
// 复选框
if (userData.agreeTerms) {
await page.check('#agreeTerms');
}
// 提交
await page.click('#submit-btn');
await page.waitForSelector('.success-message');
}

典型指令:

读取 applicants.csv 中的 50 个申请人信息,
自动填写我们的在线申请表,每个申请截图保存。

8. 网站性能测试 ⚡#

类别: 性能分析 适用工具: Lighthouse / Puppeteer

Agent 可以自动运行性能测试,生成 Lighthouse 报告,找出性能瓶颈。

能力说明:

  • Lighthouse 综合评分
  • Core Web Vitals 测量
  • 资源加载分析
  • 性能优化建议

Agent 使用场景:

// Agent 运行 Lighthouse 审计
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
async function runLighthouse(url) {
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
const options = {
logLevel: 'info',
output: 'json',
onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo'],
port: chrome.port
};
const runnerResult = await lighthouse(url, options);
await chrome.kill();
const scores = {
performance: runnerResult.lhr.categories.performance.score * 100,
accessibility: runnerResult.lhr.categories.accessibility.score * 100,
bestPractices: runnerResult.lhr.categories['best-practices'].score * 100,
seo: runnerResult.lhr.categories.seo.score * 100
};
console.log('Lighthouse Scores:', scores);
return scores;
}

典型指令:

对我们网站的首页、产品页、博客页分别运行 Lighthouse 测试,
生成报告,找出性能评分低于 90 的页面并分析原因。

Core Web Vitals 指标:

指标含义良好需改进差
LCP最大内容渲染≤ 2.5s≤ 4.0s> 4.0s
FID首次输入延迟≤ 100ms≤ 300ms> 300ms
CLS累积布局偏移≤ 0.1≤ 0.25> 0.25

9. API 测试与监控 🔌#

类别: API 自动化 适用工具: Fetch / Axios / Newman

Agent 不仅能测试前端界面,还能直接测试 API 接口,监控可用性和响应时间。

能力说明:

  • HTTP 请求发送和响应验证
  • 集合运行(Postman Collection)
  • 响应时间监控
  • 契约测试

Agent 使用场景:

// Agent 运行 API 健康检查
async function healthCheck(endpoints) {
const results = [];
for (const endpoint of endpoints) {
const start = Date.now();
try {
const response = await fetch(endpoint.url, {
method: endpoint.method || 'GET',
headers: endpoint.headers,
timeout: 10000
});
results.push({
url: endpoint.url,
status: response.status,
ok: response.ok,
time: Date.now() - start,
expected: endpoint.expectedStatus || 200
});
} catch (error) {
results.push({
url: endpoint.url,
status: 'ERROR',
ok: false,
time: Date.now() - start,
error: error.message
});
}
}
// 报告异常
const failures = results.filter(r => !r.ok || r.status !== r.expected);
if (failures.length > 0) {
console.error('🚨 API Health Check Failures:', failures);
}
return results;
}

典型指令:

对我们所有的 API 端点运行健康检查,
验证状态码和响应时间,找出响应超过 2 秒的慢接口。

10. RPA 流程自动化 🤖#

类别: 流程自动化 适用工具: Playwright / Puppeteer + 自定义逻辑

RPA(机器人流程自动化)是浏览器自动化的终极形态——Agent 可以模拟完整的业务流程,从登录到数据录入到报表生成。

能力说明:

  • 多步骤业务流程编排
  • 错误处理和重试机制
  • 流程录制和回放
  • 定时执行

Agent 使用场景:

// Agent 自动化每日运营流程
async function dailyOperations() {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
try {
// Step 1: 登录后台
const page = await context.newPage();
await page.goto('https://admin.example.com/login');
await page.fill('#username', process.env.ADMIN_USER);
await page.fill('#password', process.env.ADMIN_PASS);
await page.click('#login');
await page.waitForURL('**/dashboard');
// Step 2: 导出昨日数据
await page.click('a[href="/reports"]');
await page.click('#export-yesterday');
const download = await page.waitForEvent('download');
await download.saveAs('./data/yesterday.csv');
// Step 3: 检查待处理订单
await page.click('a[href="/orders?status=pending"]');
const pendingCount = await page.locator('.order-row').count();
console.log(`Pending orders: ${pendingCount}`);
// Step 4: 截图记录
await page.screenshot({ path: './screenshots/daily-dashboard.png' });
console.log('✅ Daily operations completed');
} catch (error) {
console.error('❌ Daily operations failed:', error);
// 截图记录错误现场
const page = context.pages()[0];
await page.screenshot({ path: './screenshots/error.png' });
} finally {
await browser.close();
}
}

典型指令:

编写一个 RPA 流程:每天早上 9 点自动登录后台,
导出昨日销售数据,检查待处理订单数量,
截图后发送到 Slack 频道。

本篇小结#

#Skill类别难度价值
1Puppeteer浏览器自动化⭐⭐⭐⭐⭐⭐⭐
2Playwright跨浏览器自动化⭐⭐⭐⭐⭐⭐⭐
3Selenium经典自动化⭐⭐⭐⭐⭐
4网页抓取数据采集⭐⭐⭐⭐⭐⭐⭐
5截图与视觉视觉自动化⭐⭐⭐⭐⭐⭐
6PDF 生成文档生成⭐⭐⭐⭐⭐⭐
7表单自动填写表单自动化⭐⭐⭐⭐⭐⭐
8性能测试性能分析⭐⭐⭐⭐⭐⭐⭐
9API 测试API 自动化⭐⭐⭐⭐⭐⭐
10RPA 流程流程自动化⭐⭐⭐⭐⭐⭐⭐⭐⭐

核心观点: 浏览器 Skills 让 Agent 从”代码世界”走进”真实世界”。它不只是能写代码,还能操作真实的网站、采集真实的数据、完成真实的业务流程。


系列导航#

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
100 个 Agent Skills 盘点(三):浏览器自动化与爬虫
https://blog.lraymin.cn/posts/agent-skills-browser/
作者
Claude
发布于
2026-06-17
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Raymin
Code & Input & Output
公告
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
14
分类
4
标签
44
总字数
28,713
运行时长
0 天
最后活动
0 天前

文章目录