Playwright Extensions and Migration
This chapter introduces the extension features of the Playwright ecosystem, including Library script mode, MCP services, Test Agents, and a guide to migrating from other frameworks to Playwright.
Playwright Library Script Mode
Playwright Library is a standalone browser automation library, suitable for scenarios outside of test runners.
Installation
npm i playwright
Typical Usage
Example
import { chromium } from 'playwright';
(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://www.example.com/');
await page.screenshot({ path: 'example.png', fullPage: true });
await browser.close();
console.log('Screenshot saved to example.png');
})();
PDF Generation
Example
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://www.example.com/');
// Generate PDF (Chromium only)
await page.pdf({
path: 'example.pdf',
format: 'A4',
margin: { top: '20px', bottom: '20px' },
});
await browser.close();
})();
Choosing Between Library Mode and Test Runner
| Scenario | Recommendation |
|---|---|
| Writing E2E tests | Playwright Test Runner |
| Web page screenshots, PDF generation | Playwright Library |
| Web data scraping | Playwright Library |
| One-off automation scripts | Playwright Library |
Introduction to Playwright MCP
The Playwright MCP (Model Context Protocol) server allows AI assistants to directly control the browser.
MCP Installation and Configuration
# 为 Claude Code 添加 Playwright MCP claude mcp add playwright npx @playwright/mcp@latest
Configure it in VS Code or other MCP clients:
Example
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
}
How MCP Works
The AI Agent perceives page content through structured accessibility snapshots.
Each piece of accessibility information has arefref identifier, and the Agent uses this ref to perform actions such as clicking and typing.
This approach does not require screenshots; it is entirely based on structured data interaction, which is fast and highly deterministic.
Playwright Test Agents
Test Agents are experimental AI-driven testing tools that can automatically generate and fix tests.
| Agent | Feature | Trigger Method |
|---|---|---|
| Planner | Automatically explore the application and generate a Markdown test plan | LLM Agent driven |
| Generator | Convert the test plan into Playwright test code | LLM Agent driven |
| Healer | Execute the test suite and automatically fix failing tests | LLM Agent driven |
Initialize Test Agents:
# 为 VS Code 初始化 npx playwright init-agents --loop=vscode # 为 Claude Code 初始化 npx playwright init-agents --loop=claude
Component Testing Overview (Experimental)
Playwright supports directly mounting and testing React/Vue components without needing a full page environment.
Example
// Mount React component
const component = await mount(
<Button title="Submit" />
);
// Assert the text displayed by the component
await expect(component).toContainText('Submit');
// Click the button
await component.click();
});
Accessibility Testing
Playwright provides assertions for accessible names and descriptions to help verify page accessibility.
Example
await expect(page.getByRole('button'))
.toHaveAccessibleName('Submit form');
// Verify the element has an accessible description
await expect(page.getByLabel('Username'))
.toHaveAccessibleDescription('Please enter a 4-16 character alphanumeric combination');
Migrating from Other Frameworks
Migrating from Puppeteer
Playwright and Puppeteer share the capabilities of the Chrome DevTools Protocol, making migration relatively simple.
| Puppeteer | Playwright |
|---|---|
puppeteer.launch() | chromium.launch() |
page.waitForSelector() | Not needed (auto-waiting) orpage.locator() |
page.$(selector) | page.locator(selector) |
page.evaluate() | page.evaluate()(same) |
page.setRequestInterception() | page.route() |
Migrating from Cypress
Playwright's Locator concept is similar to Cypress's query chaining, but there are some key differences:
| Cypress | Playwright |
|---|---|
cy.get('.class') | page.locator('.class') |
cy.contains('text') | page.getByText('text') |
cy.get('[data-cy="btn"]') | page.getByTestId('btn')(withtestIdAttribute: 'data-cy') |
cy.intercept() | page.route() |
cy.wait() | Not needed (auto-waiting) |
Migrating from Selenium
Selenium uses the WebDriver protocol, while Playwright directly controls browser protocols, resulting in significantly different API styles.
| Selenium | Playwright |
|---|---|
driver.findElement(By.id('x')) | page.locator('#x') |
driver.get(url) | page.goto(url) |
element.click() | locator.click() |
WebDriverWait | Not needed (built-in auto-waiting) |
new RemoteWebDriver() | chromium.connect(url) |
Other ExtensionsMigration advice: Don't try to migrate all tests in one step.
First choose tests for one or two core features and rewrite them with Playwright. After verification passes, gradually migrate the remaining tests.