Playwright MCP:AI驱动的浏览器自动化
Playwright MCP(Model Context Protocol)是微软推出的新一代浏览器自动化协议
·
Playwright MCP
Playwright MCP(Model Context Protocol)是微软推出的新一代浏览器自动化协议,它通过以下创新点重新定义了人机交互模式:
- 结构化数据驱动:基于可访问性树(Accessibility Tree)而非像素截图进行元素定位
- 精准操作保障:通过唯一元素引用(ref)实现确定性操作
- 多模态支持:同时支持Snapshot模式和Vision模式
- LLM原生友好:提供自然语言交互接口,完美对接大语言模型
本文将通过20+代码示例,详解如何在不同场景中使用该框架。
环境配置
VS Code 集成安装
# 标准版安装
code --add-mcp '{
"name": "playwright",
"command": "npx",
"args": ["@playwright/mcp@latest"]
}'
# 无头模式配置
code --add-mcp '{
"name": "playwright-headless",
"command": "npx",
"args": ["@playwright/mcp@latest", "--headless"]
}'
基础配置文件
创建 .mcp.config.json
:
{
"mcpServers": {
"default": {
"command": "npx",
"args": ["@playwright/mcp@latest", "--browser=chrome"]
},
"firefox": {
"command": "npx",
"args": ["@playwright/mcp@latest", "--browser=firefox"]
}
}
}
核心操作模式解析
Snapshot模式(默认)
优势:基于可访问性树的轻量化交互
// 获取页面快照
const snapshot = await mcp.execute('browser_snapshot');
// 精准元素点击
await mcp.execute('browser_click', {
element: "登录按钮",
ref: snapshot.elements.loginButton.ref
});
// 表单填写示例
await mcp.execute('browser_type', {
ref: snapshot.elements.searchInput.ref,
text: "Playwright MCP",
submit: true
});
Vision模式
适用场景:需要视觉定位的复杂交互
// 启用Vision模式服务
{
"mcpServers": {
"vision": {
"command": "npx",
"args": ["@playwright/mcp@latest", "--vision"]
}
}
}
// 坐标点击操作
await mcp.execute('browser_screen_click', {
x: 300,
y: 150
});
// 拖拽操作
await mcp.execute('browser_screen_drag', {
startX: 100,
startY: 200,
endX: 400,
endY: 200
});
场景示例
自动化表单填写
// 获取当前页面快照
const snap = await mcp.execute('browser_snapshot');
// 填写注册表单
await mcp.execute('browser_type', {
ref: snap.elements.username.ref,
text: "test_user"
});
await mcp.execute('browser_select_option', {
ref: snap.elements.country.ref,
values: ["CN"]
});
await mcp.execute('browser_click', {
ref: snap.elements.submitButton.ref
});
多标签页管理
// 创建新标签页
await mcp.execute('browser_tab_new', {
url: "https://example.com"
});
// 获取标签列表
const tabs = await mcp.execute('browser_tab_list');
// 切换至第二个标签页
await mcp.execute('browser_tab_select', {
index: 1
});
// 关闭当前标签页
await mcp.execute('browser_tab_close');
文件处理流程
// 文件上传
await mcp.execute('browser_file_upload', {
paths: ["/path/to/file1.pdf", "/path/to/image.jpg"]
});
// 保存为PDF
const pdfBuffer = await mcp.execute('browser_pdf_save');
// 等待处理完成
await mcp.execute('browser_wait', {
time: 5
});
高级功能实现
键盘事件模拟
// 组合键操作示例
await mcp.execute('browser_press_key', {
key: "Control+A"
});
// 特殊按键处理
await mcp.execute('browser_press_key', {
key: "ArrowDown"
});
历史记录管理
// 导航历史操作
await mcp.execute('browser_navigate_back');
await mcp.execute('browser_navigate_forward');
自定义传输协议
import { createServer, SSEServerTransport } from '@playwright/mcp';
const server = createServer({
launchOptions: {
headless: true,
channel: 'chrome-canary'
}
});
const transport = new SSEServerTransport("/api/events", response);
server.connect(transport);
更多推荐
所有评论(0)