Claude Code + Playwright MCP 安装与验证
这是一篇示例文章,用于测试 Astro 的文章布局。
为什么选择 Claude Code + Playwright MCP?
传统的 UI 自动化测试面临三个核心问题:
- 脚本编写效率低:需要手动编写大量定位器和断言代码
- 维护成本高:页面变化后需要人工定位失效元素并修复
- 失败诊断难:测试失败后需要人工分析日志、截图和元素状态
Claude Code + Playwright MCP 提供了一种新的解决方案。
环境准备
1. 安装 Claude Code
# 使用 npm 安装
npm install -g @anthropic-ai/claude-code
# 验证安装
claude --version
2. 安装 Playwright
# 安装 Playwright Python 库
pip install playwright pytest-playwright
# 安装浏览器
playwright install
3. 配置 MCP
创建 .claude/mcp.json:
{
"mcpServers": {
"playwright": {
"command": "python",
"args": ["-m", "playwright_mcp"],
"env": {
"HEADLESS": "false"
}
}
}
}
第一个自动化测试
创建 test_example.py:
from playwright.sync_api import Page, expect
def test_homepage(page: Page):
# 访问页面
page.goto("https://aitestclub.com")
# 验证标题
expect(page).to_have_title("AI 测研社")
# 点击导航
page.click("text=产品中心")
# 验证跳转
expect(page).to_have_url("/#products")
运行测试
# 运行测试
pytest test_example.py
# 生成报告
pytest test_example.py --html=report.html
常见问题
Q1: 浏览器无法启动?
检查浏览器是否正确安装:
playwright install --with-deps chromium
Q2: MCP 连接失败?
确认 .claude/mcp.json 路径和格式正确。
下一步
- 学习智能元素定位
- 了解 AI 断言生成
- 实践失败修复流程
相关文章: