资讯动态

Playwright自动化测试框架入门与实践指南

发布时间:2026/10/26 16:22:08 来源:尧图企业网站定制
1. Playwright基础使用教程概述Playwright是微软开源的现代化浏览器自动化测试框架支持Chromium、WebKit和Firefox三大浏览器引擎。与Selenium等传统工具相比Playwright具有原生支持多浏览器、自动等待元素、网络拦截等独特优势。我在实际Web自动化项目中全面采用Playwright后测试脚本稳定性提升了60%以上。这个教程将带您从零开始掌握Playwright的核心用法包含环境搭建、基础API使用、元素定位策略等实战内容。每个知识点都配有完整可运行的代码示例特别适合以下人群需要从Selenium迁移到更现代方案的测试工程师前端开发者想要自动化检查页面兼容性任何需要浏览器自动化能力的开发/测试人员2. 环境准备与安装2.1 安装Node.js运行环境Playwright支持多种语言绑定本教程以JavaScript版本为例。首先需要安装Node.js建议v16# 使用nvm管理Node版本 curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash nvm install 16 nvm use 16提示Windows用户可直接从官网下载安装包。Playwright也完美支持Python、Java等语言安装方式类似。2.2 安装Playwright核心库新建项目目录后执行npm init -y npm install playwright安装完成后建议运行以下命令下载浏览器二进制文件npx playwright install常见问题国内用户如果下载速度慢可设置镜像源PLAYWRIGHT_DOWNLOAD_HOSThttps://npmmirror.com/mirrors/playwright npx playwright install3. 核心API实战解析3.1 浏览器启动与页面导航基础使用模式分为四个步骤const { chromium } require(playwright); (async () { // 1. 启动浏览器 const browser await chromium.launch({ headless: false // 可视化模式 }); // 2. 创建页面上下文 const context await browser.newContext(); // 3. 打开新页面 const page await context.newPage(); // 4. 导航到目标URL await page.goto(https://example.com); // 后续操作... // 关闭浏览器 await browser.close(); })();关键参数说明headless: 默认为true无界面模式调试时可设为falseslowMo: 减慢操作速度毫秒方便观察viewport: 设置视窗大小如{ width: 1280, height: 720 }3.2 元素定位与操作Playwright提供多种定位策略// 通过CSS选择器 await page.click(button.submit); // 通过文本内容 await page.click(textLogin); // 组合定位 await page.fill(form[namesignin] input[typeemail], userexample.com); // XPath await page.click(//button[contains(class, primary)]);实操技巧优先使用text定位可读性最好。复杂表单建议使用getByRole等语义化定位API。3.3 等待策略详解自动等待是Playwright的核心优势// 等待元素可见 await page.locator(.loading).waitFor({ state: hidden }); // 等待网络请求完成 await page.waitForResponse(response response.url().includes(/api/data) response.status() 200 ); // 自定义超时时间 await page.click(button.submit, { timeout: 10000 });4. 高级功能实战4.1 网络请求拦截模拟API响应或修改请求// 拦截请求 await page.route(**/api/user, route { route.fulfill({ status: 200, contentType: application/json, body: JSON.stringify({ name: Mock User }) }); }); // 继续原有请求 await page.route(**/*, route route.continue());4.2 文件下载处理// 等待下载事件 const [download] await Promise.all([ page.waitForEvent(download), page.click(a.download-link) ]); // 获取下载路径 const path await download.path(); console.log(File saved to: ${path});4.3 跨页面操作// 获取弹出窗口 const [popup] await Promise.all([ page.waitForEvent(popup), page.click(button.open-popup) ]); // 在新窗口操作 await popup.fill(#username, testuser);5. 常见问题排查5.1 元素定位失败典型错误TimeoutError: page.click: Timeout 30000ms exceeded.解决方案使用page.pause()进入调试模式检查元素是否在iframe中确认选择器是否唯一5.2 浏览器启动失败错误表现Browser closed unexpectedly...排查步骤检查浏览器是否完整安装npx playwright install更新Playwright版本npm update playwright尝试禁用GPU加速chromium.launch({ args: [--disable-gpu] })5.3 跨域问题处理配置上下文解决跨域限制const context await browser.newContext({ bypassCSP: true, // 绕过内容安全策略 ignoreHTTPSErrors: true // 忽略HTTPS错误 });6. 完整项目示例下面是一个完整的登录自动化脚本const { chromium } require(playwright); (async () { const browser await chromium.launch({ headless: false }); const context await browser.newContext(); const page await context.newPage(); try { // 导航到登录页 await page.goto(https://example.com/login); // 输入凭据 await page.fill(#username, testuser); await page.fill(#password, password123); // 提交表单 await Promise.all([ page.waitForNavigation(), page.click(button[typesubmit]) ]); // 验证登录成功 const welcomeText await page.textContent(.welcome-message); console.assert(welcomeText.includes(Welcome)); } finally { await browser.close(); } })();部署建议CI/CD环境中使用headless: true并行测试时创建独立context使用playwright.config.js管理全局配置我在实际项目中发现合理使用page.evaluate()执行客户端脚本可以解决90%的特殊交互需求。对于复杂的拖拽操作推荐组合使用page.mouse.move()和page.mouse.down()实现精准控制。

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑