Playwright 第一个脚本(2025 年最新版)
恭喜你开始 Playwright 之旅!以下是编写和运行你的第一个 Playwright 脚本的完整指南。我们将使用 Node.js/TypeScript 版本(最主流,推荐新手),脚本会启动浏览器、导航到 Playwright 官网、截取页面截图。这基于官方文档的经典示例,简单可靠。
1. 前提条件
- 已完成安装(参考前文):
npm i -D @playwright/test和npx playwright install。 - 创建一个新文件:
first-script.spec.ts(放在tests/目录下,如果没有则新建)。
2. 脚本代码(first-script.spec.ts)
这是一个使用 Playwright Test 框架的测试脚本(推荐方式,比纯 Library 更结构化)。它会:
- 启动 Chromium 浏览器(无头模式)。
- 导航到 https://playwright.dev/。
- 截取页面截图保存为
example.png。 - 断言页面标题正确。
import { test, expect } from '@playwright/test';
test('第一个 Playwright 脚本:导航到官网并截图', async ({ page }) => {
// 导航到 Playwright 官网
await page.goto('https://playwright.dev/');
// 截取页面截图
await page.screenshot({ path: 'example.png' });
// 断言页面标题(Web-First 断言,自动重试)
await expect(page).toHaveTitle(/Playwright/);
console.log('脚本执行成功!截图已保存为 example.png');
});
- 解释:
test():定义一个测试用例。page.goto():导航到 URL(自动等待页面加载)。page.screenshot():截图保存到当前目录。expect(page).toHaveTitle():断言标题包含 “Playwright”(可靠的 Web-First 断言)。
3. 运行脚本
在项目根目录打开终端,执行:
npx playwright test first-script.spec.ts
- 预期输出:
Running 1 test using 1 worker
[ Chromium 123.0.0 / linux ] 1 passed (2s)
1 passed (2s)
- 脚本运行后,会在项目目录生成
example.png截图文件。 - 如果想看到浏览器界面(调试用),添加
--headed参数:
npx playwright test first-script.spec.ts --headed
4. Python 版脚本(如果你更喜欢 Python)
如果使用 Python 版(pip install playwright),创建一个 first_script.py:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # headless=False 显示浏览器
page = browser.new_page()
page.goto("https://playwright.dev/")
page.screenshot(path="example.png")
print(page.title()) # 输出页面标题
browser.close()
运行:python first_script.py。
5. 常见问题与提示
- 无截图生成?检查权限,确保目录可写。
- 浏览器不启动?运行
npx playwright install chromium重新下载。 - 扩展脚本:添加交互,如
await page.fill('input[name="q"]', 'Hello Playwright');(在 Google 搜索)。 - 下一步:试试
npx playwright codegen https://playwright.dev/录制操作自动生成代码。
这个脚本只需 5 分钟就能跑起来!运行成功后,你已掌握 Playwright 的核心:浏览器控制 + 自动化操作。如果需要更多示例(如表单填写、API Mock)或调试帮助,告诉我你的语言偏好(JS/Python)。