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

// Screenshot script
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

import { chromium } from 'playwright';

(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

ScenarioRecommendation
Writing E2E testsPlaywright Test Runner
Web page screenshots, PDF generationPlaywright Library
Web data scrapingPlaywright Library
One-off automation scriptsPlaywright 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.

AgentFeatureTrigger Method
PlannerAutomatically explore the application and generate a Markdown test planLLM Agent driven
GeneratorConvert the test plan into Playwright test codeLLM Agent driven
HealerExecute the test suite and automatically fix failing testsLLM 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

test('Button component test', async ({ mount }) => {
  // 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

// Verify the element has the correct accessible name
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.

PuppeteerPlaywright
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:

CypressPlaywright
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.

SeleniumPlaywright
driver.findElement(By.id('x'))page.locator('#x')
driver.get(url)page.goto(url)
element.click()locator.click()
WebDriverWaitNot needed (built-in auto-waiting)
new RemoteWebDriver()chromium.connect(url)

Migration 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.

Other Extensions