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. 正确的邮箱和密码 → 应该跳转到 dashboard2. 错误的密码 → 应该显示错误提示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:
| 特性 | Puppeteer | Playwright |
|---|---|---|
| 浏览器支持 | Chrome/Firefox | Chrome/Firefox/Safari |
| 维护方 | Microsoft | |
| 自动等待 | 需手动配置 | 内置 |
| 代码生成 | ❌ | ✅ Codegen |
| 并行测试 | 一般 | 优秀 |
| 社区生态 | 极丰富 | 快速成长 |
3. Selenium MCP Server 🌐
类别: 经典浏览器自动化 协议: MCP
Selenium 是浏览器自动化的”老前辈”,虽然不如 Puppeteer/Playwright 现代,但在企业环境中仍然广泛使用。
能力说明:
- WebDriver 协议控制浏览器
- 支持几乎所有编程语言
- 企业级测试框架集成
- Grid 分布式测试
Agent 使用场景:
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom 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。常用抓取工具对比:
| 工具 | 语言 | 特点 | 适用场景 |
|---|---|---|---|
| Cheerio | JS | 快速、轻量 | 静态页面 |
| BeautifulSoup | Python | 简单易用 | 快速原型 |
| Scrapy | Python | 全功能框架 | 大规模采集 |
| Puppeteer | JS | 渲染页面 | 动态页面 |
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 生成月度报告 PDFconst 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 | 类别 | 难度 | 价值 |
|---|---|---|---|---|
| 1 | Puppeteer | 浏览器自动化 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 2 | Playwright | 跨浏览器自动化 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 3 | Selenium | 经典自动化 | ⭐⭐ | ⭐⭐⭐ |
| 4 | 网页抓取 | 数据采集 | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 5 | 截图与视觉 | 视觉自动化 | ⭐⭐ | ⭐⭐⭐⭐ |
| 6 | PDF 生成 | 文档生成 | ⭐⭐ | ⭐⭐⭐⭐ |
| 7 | 表单自动填写 | 表单自动化 | ⭐⭐ | ⭐⭐⭐⭐ |
| 8 | 性能测试 | 性能分析 | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 9 | API 测试 | API 自动化 | ⭐⭐ | ⭐⭐⭐⭐ |
| 10 | RPA 流程 | 流程自动化 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
核心观点: 浏览器 Skills 让 Agent 从”代码世界”走进”真实世界”。它不只是能写代码,还能操作真实的网站、采集真实的数据、完成真实的业务流程。
系列导航
- 👈 上一篇: 第二篇:数据库与数据存储
- 👉 下一篇: 第四篇:搜索与信息获取
- 📖 系列目录:
- 第一篇:代码审查与质量守护
- 第二篇:数据库与数据存储
- ✅ 第三篇:浏览器自动化与爬虫(你在这里)
- 第四篇:搜索与信息获取
- 第五篇:云服务与 DevOps
- 第六篇:知识管理与 RAG
- 第七篇:版本控制与协作
- 第八篇:文档与文件处理
- 第九篇:通信与通知集成
- 第十篇:创意与可视化
支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!