一、Playwright 和 MCP协议 是什么?

Playwright:跨浏览器自动化的“瑞士军刀”。Playwright是微软开源的自动化测试工具,其核心优势在于:

跨浏览器支持:原生兼容Chromium(Chrome/Edge)、Firefox、WebKit(Safari),无需手动安装驱动

自动等待机制:操作前自动等待元素加载,减少硬编码sleep

智能选择器:支持Shadow DOM穿透和动态元素定位,降低维护成本

多场景覆盖:支持文件上传下载、跨域操作、移动端模拟等复杂需求

MCP协议:标准化AI与工具的“对话”

MCP协议通过定义统一的通信标准,让LLM能够无缝调用外部工具(如浏览器、数据库、本地文件)。其核心价值体现在:

要添加 Playwright 的 MCP(Microsoft Playwright Component Testing),你需要通过 npm 安装相关包并进行配置。以下是具体步骤:

标准化交互:开发者只需实现一次MCP Server,即可适配所有支持MCP的客户端(如WindSurf、Cline)。
动态灵活性:支持实时生成指令,例如根据页面状态动态调整操作流程。
安全性:内置权限控制,防止LLM越权访问敏感数据。

以Playwright的MCP Server为例,其工作流程如下:
指令接收:LLM发送自然语言描述(如“点击登录按钮”)。
指令解析:将自然语言转化为Playwright的API调用(如page.click("#login"))。
结果返回:将操作结果(截图、日志等)反馈给LLM。

二、Playwright+mcp如何“快速”实现浏览器自动化?

1. 安装 Playwright MCP 包

环境搭建

1、安装Playwright

复制代码

安装Python环境
:确保Python版本≥3.7(推荐3.8+)
pip install playwright
python -m playwright install
#版本不匹配
playwright install --force chrome
安装Playwright Test for VSCode插件
:
在VS Code扩展商店搜索并安装"Playwright Test for VSCode"

复制代码

2、部署MCP Server

npx @playwright/mcp@latest
#或者
npm install -g @playwright/mcp
启动
npx @playwright/mcp@latest

客户端配置(以VSCode Cline为例)

安装Cline插件

image

打开终端(命令提示符或 PowerShell),在你的项目目录中运行以下命令:

code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'

在运行上诉命令时出现了一系列问题,尝试多种输入方式始终无法正确配置————这里我先跳过,等以后找到真正的解决方案的时候再来添加相关内容

复制代码

PS C:\Users\5185> code --add-mcp "{\"name\":\"playwright\",\"command\":\"npx\",\"args\":[\"@playwright/mcp@latest\"]}"
Invalid JSON '{\': SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)

PS C:\Users\5185> code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'
Invalid JSON '{name:playwright,command:npx,args:[@playwright/mcp@latest]}': SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)

PS C:\Users\5185> code --add-mcp "`"name`":`"playwright`",`"command`":`"npx`",`"args`":[`"@playwright/mcp@latest`"]}"
Invalid JSON 'name:playwright,command:npx,args:[@playwright/mcp@latest]}': SyntaxError: Unexpected token 'a', "name:playwr"... is not valid JSON

PS C:\Users\5185> $mcpConfig = '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'
PS C:\Users\5185> code --add-mcp $mcpConfig
Invalid JSON '{name:playwright,command:npx,args:[@playwright/mcp@latest]}': SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)

复制代码

  1. 打开 VS Code
  2. 按下 Ctrl+Shift+P 打开命令面板
  3. 输入并执行 Extensions: Install Extensions
  4. 搜索 Playwright 扩展并安装(由 Microsoft 官方发布)
  5. 安装完成后,重新启动 VS Code,MCP 相关功能会自动配置

先用上述的方式跳过命令行参数传递,直接通过 VS Code 图形界面安装扩展,避免 JSON 解析问题

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐