name: playwright description: 微软开发的跨浏览器自动化框架。使用单一API支持Chromium、Firefox和WebKit,用于测试、爬虫和自动化。 metadata: short-description: 跨浏览器自动化框架 source: repository: https://github.com/microsoft/playwright license: Apache-2.0 stars: 68k+
Playwright 工具
描述
用于测试、网页抓取和网络自动化的跨浏览器自动化框架,支持 Chromium、Firefox 和 WebKit。
来源
- 代码仓库: microsoft/playwright
- 许可证: Apache-2.0
- 维护者: Microsoft
安装
npm install playwright
npx playwright install # 安装浏览器
使用示例
浏览器自动化
import { chromium, firefox, webkit } from 'playwright';
async function automateTask() {
// 启动任意浏览器
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 1920, height: 1080 },
userAgent: '自定义用户代理',
});
const page = await context.newPage();
await page.goto('https://example.com');
// 点击、输入、交互
await page.click('button.login');
await page.fill('input[name="email"]', 'user@example.com');
await page.fill('input[name="password"]', 'password123');
await page.click('button[type="submit"]');
// 等待导航
await page.waitForURL('**/dashboard');
await browser.close();
}
截图与PDF
async function captureContent(url: string) {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(url);
// 截图
await page.screenshot({
path: 'screenshot.png',
fullPage: true,
});
// PDF (仅限Chromium)
await page.pdf({
path: 'document.pdf',
format: 'A4',
margin: { top: '1cm', bottom: '1cm' },
});
await browser.close();
}
使用定位器进行网页抓取
async function scrapeProducts(url: string) {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(url);
// 使用定位器进行可靠的元素选择
const products = await page.locator('.product-card').all();
const data = await Promise.all(products.map(async (product) => ({
name: await product.locator('.name').textContent(),
price: await product.locator('.price').textContent(),
rating: await product.locator('.rating').getAttribute('data-value'),
})));
await browser.close();
return data;
}
API测试
import { request } from 'playwright';
async function testAPI() {
const context = await request.newContext({
baseURL: 'https://api.example.com',
extraHTTPHeaders: {
'Authorization': 'Bearer token123',
},
});
// GET 请求
const response = await context.get('/users');
const users = await response.json();
// POST 请求
const createResponse = await context.post('/users', {
data: { name: 'John', email: 'john@example.com' },
});
await context.dispose();
}
端到端测试
import { test, expect } from '@playwright/test';
test('用户登录', async ({ page }) => {
await page.goto('/login');
await page.fill('[name="email"]', 'test@example.com');
await page.fill('[name="password"]', 'password');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('h1')).toHaveText('欢迎');
});
标签
浏览器, 测试, 自动化, 端到端测试, 网页抓取
兼容性
- Codex: ✅
- Claude Code: ✅