Playwright 现代 Web 自动化测试简明教程
Playwright 作为现代 Web 自动化测试框架的优势,包括跨引擎支持、智能等待及多语言特性。内容涵盖安装配置、基础 API 使用、常见测试场景如元素定位、网络请求等待、弹窗处理及移动端模拟。此外还详细说明了 CI 集成方法以及结合 MCP 协议实现 AI 辅助测试的新兴用法,适合希望提升测试效率的开发者参考。

Playwright 作为现代 Web 自动化测试框架的优势,包括跨引擎支持、智能等待及多语言特性。内容涵盖安装配置、基础 API 使用、常见测试场景如元素定位、网络请求等待、弹窗处理及移动端模拟。此外还详细说明了 CI 集成方法以及结合 MCP 协议实现 AI 辅助测试的新兴用法,适合希望提升测试效率的开发者参考。

在 Web 自动化测试领域,Selenium 曾长期占据主流,但面对现代前端框架(React/Vue/Next.js)、复杂 SPA 应用和多端适配需求,其局限性逐渐凸显。Microsoft 推出的 Playwright 框架,凭借跨引擎、跨平台、智能化的特性,成为新一代自动化测试的优选方案。
相比于传统的 Selenium 或 Cypress,Playwright 具有以下优势:
在已有 Node.js 环境的项目中,执行以下命令一键初始化 Playwright:
npm init playwright@latest
执行后,脚本会引导你完成以下配置:
tests)。npx playwright install)。Playwright 的 API 非常直观。在 tests/example.spec.ts 中:
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
// 期待标题包含 "Playwright"
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');
// 点击 "Get started" 链接
await page.getByRole('link', { name: 'Get started' }).click();
// 期待 URL 包含 intro
await expect(page).toHaveURL(/.*intro/);
});
Playwright 推荐使用 page.getByRole 或 page.getByText 等面向用户的定位方式,这能使测试更具鲁棒性。
// 填写表单
await page.getByLabel('用户名').fill('admin');
await page.getByLabel('密码').fill('123456');
// 点击按钮
await page.getByRole('button', { name: '登录' }).click();
在现代单页应用(SPA)中,等待特定的接口返回是非常常见的需求。
// 等待接口返回
const [response] = await Promise.all([
page.waitForResponse(resp => resp.url().includes('/api/login') && resp.status() === 200),
page.getByRole('button', { name: '登录' }).click(),
]);
Playwright 能够轻松处理 JavaScript 警告框(Dialog)和嵌套的 Iframe。
// 处理 Dialog
page.on('dialog', dialog => dialog.accept());
await page.getByRole('button', { name: '删除' }).click();
// 进入 Iframe 交互
const frame = page.frameLocator('#my-iframe');
await frame.getByText('确认提交').click();
Playwright 提供了非常精细的键盘模拟能力,不仅可以输入文本,还能模拟单个按键及组合键。
// 聚焦并输入文本
await page.getByLabel('搜索').focus();
await page.keyboard.type('Playwright', { delay: 100 });
// 模拟真实打字速度
// 按下回车键
await page.keyboard.press('Enter');
// 组合键:全选并删除 (Windows/Linux 用 Control, macOS 用 Meta)
await page.keyboard.press('Control+A');
await page.keyboard.press('Backspace');
Playwright 生态内置了大量的设备预设,可以轻松模拟特定的手机或平板环境,并支持精细控制地理位置、语言和系统权限。
import { test, devices } from '@playwright/test';
test('iPhone 14 移动端模拟测试', async ({ browser }) => {
// 使用内置设备预设
const context = await browser.newContext({
...devices['iPhone 14'],
locale: 'zh-CN',
timezoneId: 'Asia/Shanghai',
geolocation: { longitude: 116.39, latitude: 39.9 },
permissions: ['geolocation'] // 授予地理位置权限
});
const page = await context.newPage();
await page.goto('https://maps.google.com');
// 验证页面是否根据模拟坐标显示
await context.close();
});
npx playwright testnpx playwright test --project=chromiumnpx playwright test --headednpx playwright test --uinpx playwright show-reportPlaywright 提供了一项非常有趣的功能:直接对安卓设备上的 Chrome 或 WebView 进行自动化。
adb devices)。const { _android: android } = require('playwright');
(async () => {
// 连接到安卓设备
const [device] = await android.devices();
console.log(`Model: ${device.model()}`);
// 启动 Chrome
await device.shell('am force-stop com.android.chrome');
const context = await device.launchBrowser();
const page = await context.newPage();
await page.goto('https://github.com/microsoft/playwright');
console.log(await page.title());
await device.screenshot({ path: 'android-screenshot.png' });
await context.close();
await device.close();
})();
注:此功能目前仍处于实验阶段。
Playwright 与 GitHub Actions 集成非常简单。如果你在安装时选择了添加 GitHub Actions 工作流,它会为你生成 .github/workflows/playwright.yml:
name: Playwright Tests
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: lts/*
- name: Install dependencies
run: npm ci
- name: Install Playwright Browsers
run: npx playwright install --with-deps
- name: Run Playwright tests
run: npx playwright test
- uses: actions/upload-artifact@v4
在现代开发流程中,我们可以利用 Model Context Protocol (MCP) 将 Playwright 的自动化能力暴露给 AI Agent。
通过配置 Playwright MCP 服务,AI 可以:
要在 GitHub Copilot 或其他支持 MCP 的环境中使用,你可以:
@mcp playwright 并下载安装相应的 MCP 服务器插件。一旦配置完成,你就可以直接在 Chat 窗口中命令 AI:'帮我打开 xxx 网站并截个图',或者'在这个页面执行一个登录流程'。
Playwright 凭借高性能、智能化、全场景覆盖的特性,完美适配现代 Web 应用的自动化测试需求。从基础的页面交互到复杂的移动端 / 真机测试,从本地调试到 CI 集成,再到 AI 协同提效,Playwright 构建了完整的自动化测试生态。相比 Selenium,它更简洁、更稳定、更贴合现代开发流程,是值得投入学习的下一代自动化测试框架。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online