playwright

microsoftApache-2.0活跃维护

用一套 API 同时驱动 Chromium、Firefox 和 WebKit 的浏览器自动化与端到端测试框架,适合写跨浏览器测试和网页抓取脚本。

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

v1.65.0发布于 2026-11-05 18:25 UTC99,706star +216 / 7 天6,831fork同步于 2026-11-10 05:17 UTC

怎么上手

从 README 代码块原样提取,可能是其中一种安装方式
npm init playwright@latest
npm i -D @playwright/test
npx playwright install
npx playwright test
硬件要求

README 没有说明硬件要求。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

这个项目的说明还在生成中,先参考下面「最近发版」和 README。

最近发版

5 个版本v1.65.0
  1. v1.65.0最新正式版2026-11-05 · 2026-11-05 18:25 UTC

    🥟 Run tests with Bun

    The test runner now runs under Bun. Bun transpiles your TypeScript test files itself, so Playwright does not use Babel or its compilation cache. Pass the --bun flag, because without it bunx playwright test runs on Node.js:

    bunx --bun playwright test
    

    Our CI runs the test runner tests under Bun 1.4.3 on Linux. Some features work differently under Bun:

    • There is no watch mode. UI mode does not run tests again when files change, and --only-changed does not follow imports.
    • Bun loads modules itself, so --tsconfig and the JSX options in tsconfig.json have no effect, and custom ESM loaders are not supported.
    • Stack traces do not include async frames, and API names do not include the class name: click instead of locator.click. This changes some step locations, step titles and error messages.
    • Console output of a test does not get into the trace and UI mode.

    🚨 Reports with only failures

    New failures reporter prints failures and successful retries as they occur, followed by a summary, without progress output.

    New onlyFailures option of the HTML, JSON and JUnit reporters keeps only tests with unexpected outcomes, flaky tests and interrupted tests:

    // playwright.config.ts
    import { defineConfig } from '@playwright/test';
    
    export default defineConfig({
      reporter: [
        ['failures'],
        ['html', { onlyFailures: true }],
      ],
    });
    

    🎯 Test runner

    • New built-in -exclusive- test lock runs a test only when no other tests are running. All other tests continue to run in parallel with each other:

      test('restart the server', { lock: '-exclusive-' }, async () => {
        // No other test runs while this one is running.
      });
      
    • test.skip(), test.fixme(), test.fail() and test.slow() now accept only a description. It is recorded in the test annotation:

      test('upload a file', async ({ page }) => {
        test.skip('Not implemented yet');
      });
      
    • New PLAYWRIGHT_TRANSFORM_CACHE_DIR environment variable sets the directory for transpiled test files, for example on a Linux machine shared with other users.

    New APIs

    Breaking Changes ⚠️

    • TypeScript class fields now follow useDefineForClassFields from your tsconfig.json, the same as tsc. It is enabled for ES2022 and later targets, and when target is not specified. A field initializer that reads a constructor parameter property now fails, because the initializer runs first:

      class LoginPage {
        // TypeError: Cannot read properties of undefined (reading 'getByRole')
        readonly submit = this.page.getByRole('button', { name: 'Submit' });
      
        constructor(private readonly page: Page) {}
      }
      

      Move the initialization to the constructor, or set "useDefineForClassFields": false in your tsconfig.json.

    • Actions such as [locator.click()](https://playwright.dev/docs/api/class-locator#locator-

  2. v1.64.12026-10-14 · 2026-10-14 11:51 UTC
    查看更新说明

    Bug Fixes

    • #43247 [Bug]: _electron.launch intermittently loses a packaged app's first window since 1.64.0
    • #43242 [Regression]: Chromium 155+ aborts a preflighted cross-origin redirect whenever any route is registered (net::ERR_ABORTED)
  3. v1.64.02026-10-07 · 2026-10-07 20:40 UTC
    查看更新说明

    🧰 WebMCP

    New page.webmcp and frame.webmcp give access to the tools that a page registers through the experimental WebMCP browser API, so you can test them like any other part of your app:

    const browser = await chromium.launch({ args: ['--enable-features=WebMCP'] });
    const page = await browser.newPage();
    await page.goto('https://example.com');
    
    for (const tool of await page.webmcp.tools())
      console.log(tool.name, tool.description);
    
    const result = await page.webmcp.callTool('add', { a: 2, b: 40 });
    console.log(result.content[0].text); // "42"
    

    Playwright MCP also supports WebMCP by default, with page-defined tools offered to the agent as webmcp_<tool>. Pass --no-webmcp to opt out.

    playwright-cli exposes them as well:

    playwright-cli webmcp-list
    playwright-cli webmcp-call search_catalog --params '{"query":"cats"}'
    

    🎬 Better videos

    Videos can now be recorded at a custom frame rate, and the decorations for actions are styled with plain CSS:

    // playwright.config.ts
    import { defineConfig } from '@playwright/test';
    
    export default defineConfig({
      use: {
        video: {
          mode: 'on',
          size: { width: 1920, height: 1080 },
          fps: 60,
          show: {
            actions: {
              style: {
                point: 'width: 20px; height: 20px; border-radius: 50%; background: red',
                highlight: 'outline: 2px solid #333; background: rgba(0, 128, 255, .15)',
                title: 'font-size: 16px',
              },
            },
          },
        },
      },
    });
    
    • New fps option in testOptions.video, recordVideo and screencast.start(). Firefox and WebKit currently capture up to 25 frames per second.
    • New style option takes CSS declarations for the point marker, the target highlight and the action title. It replaces the fontSize option, which is now deprecated.
    • The cursor stays visible at the last action point, survives navigations and travels along a natural, eased path.
    • Videos are encoded with VP9 instead of VP8, which takes less CPU and produces smaller files of the same or better quality.
    • All video options are also available in Playwright MCP and playwright-cli.

    🎯 Test runner

    • New testProject.default option keeps a project in the config without running it by default. You can configure every browser you care about, and let a plain npx playwright test run just your favourite one:

      // playwright.config.ts
      import { defineConfig, devices } from '@playwright/test';
      
      export default defineConfig({
        projects: [
          { name: 'chromium', use: devices['Desktop Chrome'] },
          { name: 'firefox', use: devices['Desktop Firefox'], default: false },
          { name: 'webkit', use: devices['Desktop Safari'], default: false },
        ],
      });
      
      npx playwright test                     # runs chromium only
      npx playwright test --project=firefox   # runs firefox
      npx playwright test --project="*"       # runs all three, for example on CI
      
    • New --shuffle command line option schedules tests in a random order, which helps to find tests that accidentally depend on each other.

      npx playwri
      
  4. v1.63.02026-09-04 · 2026-09-04 22:40 UTC
    查看更新说明

    🔒 Test locks

    Tests that access a shared resource — an external service, a global account setting — can now declare a named lock. Tests that share a lock name never run concurrently, across files, workers and projects, while everything else keeps running in parallel:

    test('update user settings', { lock: 'user-settings' }, async ({ page }) => {
      // never runs at the same time as other tests holding 'user-settings'
    });
    

    A test can hold multiple locks, and test.describe() accepts a lock for the whole group. Learn more about test locks.

    🪟 Locate across frames

    page.frameLocator() and frame.frameLocator() called without a selector search in any frame of the subtree, so you no longer need to locate the iframe first:

    // Finds the button in any frame on the page.
    await page.frameLocator().getByRole('button').click();
    

    The rest of the locator resolves inside a single frame, just like a regular locator, and an error is thrown when it matches elements in several frames.

    👁️ Visible-only locators

    New locator.visible() returns a locator that matches only visible elements. It is the recommended replacement for the :visible CSS pseudo-class:

    await page.locator('button').visible().click();
    

    🧾 Step params and subtitles

    Steps now carry structured data for reporters. Playwright API steps report the target locator and call arguments, and test.step() accepts subtitle and params options for your own steps:

    await test.step('Login', async () => {
      // ...
    }, { subtitle: 'as admin', params: { user: 'admin' } });
    

    Reporters receive them via testStep.subtitle and testStep.params. For Playwright API steps, the subtitle is the locator or the navigation url — for example, Click with subtitle getByRole('button'). Both are rendered next to the step title in the trace viewer and the HTML report.

    🖼️ Aria and screen snapshots in traces

    The snapshots option of tracing.start() and the testOptions.trace fixture option now accept an object selecting what to capture on every action:

    // playwright.config.ts
    export default defineConfig({
      use: {
        trace: {
          mode: 'on',
          snapshots: { dom: true, aria: true, screen: true }
        },
      },
    });
    

    With aria and screen snapshots recorded, the new Display Aria mode in the trace viewer shows the action screenshot side by side with the aria snapshot, and hovering an aria node highlights it on the screenshot.

    New APIs

    Browser and Context

    • httpCredentials now also accepts an array of credentials. The first entry matching the request origin is used, and entries without an origin match any request.
    • New option opfs includes the origin private file system in the storage state, so it can be persisted and restored into later contexts.
    • New events page.on('dialogclosed') and [browserContext.on('dialogclosed')](https
  5. v1.62.12026-07-30 · 2026-07-30 16:35 UTC
    查看更新说明

    Bug Fixes

    • #41989 [Regression]: tsconfig "extends" bare specifier isn't resolved via node_modules walk-up like tsc (fatal since 1.62)
    • #41998 [Regression]: directory-form tsconfig project references ("path": "../pkg") fail to resolve (fatal since 1.62)
    • #41985 Accessibility snapshot drops button name when text is nested inside spans with aria-hidden SVG
    • #42000 [Regression]: page.evaluate() arg of a branded primitive type (string & { brand }) no longer type-checks since 1.62
    • #42013 [BUG]Image-type actionable elements are not presented in the snapshot.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    🎭 Playwright

    npm version Chromium version Firefox version WebKit version Join Discord

    Documentation | API reference

    Playwright is a framework for web automation and testing. It drives Chromium, Firefox, and WebKit with a single API — in your tests, in your scripts, and as a tool for AI agents.

    Get Started

    Choose the path that fits your workflow:

    Best forInstall
    Playwright TestEnd-to-end testingnpm init playwright@latest
    Playwright CLICoding agents (Claude Code, Copilot)npm i -g @playwright/cli@latest
    Playwright MCPAI agents and LLM-driven automationnpx @playwright/mcp@latest
    Playwright LibraryBrowser automation scriptsnpm i playwright
    VS Code ExtensionTest authoring and debugging in VS CodeInstall from Marketplace

    Playwright Test

    Playwright Test is a full-featured test runner built for end-to-end testing. It runs tests across Chromium, Firefox, and WebKit with full browser isolation, auto-waiting, and web-first assertions.

    Install

    npm init playwright@latest
    

    Or add manually:

    npm i -D @playwright/test
    npx playwright install
    

    Write a test

    import { test, expect } from '@playwright/test';
    
    test('has title', async ({ page }) => {
      await page.goto('https://playwright.dev/');
      await expect(page).toHaveTitle(/Playwright/);
    });
    
    test('get started link', async ({ page }) => {
      await page.goto('https://playwright.dev/');
      await page.getByRole('link', { name: 'Get started' }).click();
      await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
    });
    

    Run tests

    npx playwright test
    

    Tests run in parallel across all configured browsers, in headless mode by default. Each test gets a fresh browser context — full isolation with near-zero overhead.

    Key capabilities

    Auto-wait and web-first assertions. No artificial timeouts. Playwright waits for elements to be actionable, and assertions automatically retry until conditions are met.

    Locators. Find elements with resilient locators that mirror how users see the page:

    page.getByRole('button', { name: 'Submit' })
    page.getByLabel('Email')
    page.getByPlaceholder('Search...')
    page.getByTestId('login-form')
    

    Test isolation. Each test runs in its own browser context — equivalent to a fresh browser profile. Save authentication state once and reuse it across tests:

    // Save state after login
    await page.context().storageState({ path: 'auth.json' });
    
    // Reuse in other tests
    test.use({ storageState: 'auth.json' });
    

    Tracing. Capture execution traces, screenshots, and videos on failure. Inspect every action, DOM snapshot, network request, and console message in the Trace Viewer:

    // playwright.config.ts
    export default defineConfig({
      use: {
        trace: 'on-first-retry',
      },
    });
    
    npx playwright show-trace trace.zip
    

    Parallelism. Tests run in parallel by default across all configured browsers.

    Full testing documentation


    Playwright CLI

    Playwright CLI is a command-line interface for browser automation designed for coding agents. It's more token-efficient than MCP — commands avoid loading large tool schemas and accessibility trees into the model context.

    Install

    npm install -g @playwright/cli@latest
    

    Optionally install skills for richer agent integration:

    playwright-cli install --skills
    

    Usage

    Point your coding agent at a task:

    Test the "add todo" flow on https://demo.playwright.dev/todomvc using playwright-cli.
    Take screenshots for all successful and failing scenarios.
    

    Or run commands directly:

    playwright-cli open https://demo.playwright.dev/todomvc/ --headed
    playwright-cli type "Buy groceries"
    playwright-cli press Enter
    playwright-cli screenshot
    

    Session monitoring

    Use playwright-cli show to open a visual dashboard with live screencast previews of all running browser sessions. Click any session to zoom in and take remote control.

    playwright-cli show
    

    Full CLI documentation | GitHub


    Playwright MCP

    The Playwright MCP server gives AI agents full browser control through the Model Context Protocol. Agents interact with pages using structured accessibility snapshots — no vision models or screenshots required.

    Setup

    Add to your MCP client (VS Code, Cursor, Claude Desktop, Windsurf, etc.):

    {
      "mcpServers": {
        "playwright": {
          "command": "npx",
          "args": ["@playwright/mcp@latest"]
        }
      }
    }
    

    One-click install for VS Code:

    For Claude Code:

    claude mcp add playwright npx @playwright/mcp@latest
    

    How it works

    Ask your AI assistant to interact with any web page:

    Navigate to https://demo.playwright.dev/todomvc and add a few todo items.
    

    The agent sees the page as a structured accessibility tree:

    - heading "todos" [level=1]
    - textbox "What needs to be done?" [ref=e5]
    - listitem:
      - checkbox "Toggle Todo" [ref=e10]
      - text: "Buy groceries"
    

    It uses element refs like e5 and e10 to click, type, and interact — deterministically and without visual ambiguity. Tools cover navigation, form filling, screenshots, network mocking, storage management, and more.

    Full MCP documentation | GitHub


    Playwright Library

    Use playwright as a library for browser automation scripts — web scraping, PDF generation, screenshot capture, and any workflow that needs programmatic browser control without a test runner.

    Install

    npm i playwright
    

    Examples

    Take a screenshot:

    import { chromium } from 'playwright';
    
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto('https://playwright.dev/');
    await page.screenshot({ path: 'screenshot.png' });
    await browser.close();
    

    Generate a PDF:

    import { chromium } from 'playwright';
    
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto('https://playwright.dev/');
    await page.pdf({ path: 'page.pdf', format: 'A4' });
    await browser.close();
    

    Emulate a mobile device:

    import { chromium, devices } from 'playwright';
    
    const browser = await chromium.launch();
    const context = await browser.newContext(devices['iPhone 15']);
    const page = await context.newPage();
    await page.goto('https://playwright.dev/');
    await page.screenshot({ path: 'mobile.png' });
    await browser.close();
    

    Intercept network requests:

    import { chromium } from 'playwright';
    
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.route('**/*.{png,jpg,jpeg}', route => route.abort());
    await page.goto('https://playwright.dev/');
    await browser.close();
    

    Library documentation | API reference


    VS Code Extension

    The Playwright VS Code extension brings test running, debugging, and code generation directly into your editor.

    Run and debug tests from the editor with a single click. Set breakpoints, inspect variables, and step through test execution with a live browser view.

    Generate tests with CodeGen. Click "Record new" to open a browser — navigate and interact with your app while Playwright writes the test code for you.

    Pick locators. Hover over any element in the browser to see the best available locator, then click to copy it to your clipboard.

    Trace Viewer integration. Enable "Show Trace Viewer" in the sidebar to get a full execution trace after each test run — DOM snapshots, network requests, console logs, and screenshots at every step.

    Install the extension | VS Code guide


    Cross-Browser Support

    LinuxmacOSWindows
    Chromium1 158.0.8127.18:white_check_mark::white_check_mark::white_check_mark:
    WebKit 27.2:white_check_mark::white_check_mark::white_check_mark:
    Firefox 159.0:white_check_mark::white_check_mark::white_check_mark:

    Headless and headed execution on all platforms. 1 Uses Chrome for Testing by default.

    Other Languages

    Playwright is also available for Python, .NET, and Java.

    Resources