Skip to main content

介绍

¥Introduction

Playwright Library 提供用于启动浏览器并与浏览器交互的统一 API,而 Playwright Test 则提供所有这些以及完全托管的端到端测试运行程序和体验。

¥Playwright Library provides unified APIs for launching and interacting with browsers, while Playwright Test provides all this plus a fully managed end-to-end Test Runner and experience.

在大多数情况下,对于端到端测试,你需要直接使用 @playwright/test(Playwright 测试),而不是 playwright(Playwright 库)。要开始 Playwright 测试,请遵循 入门指南

¥Under most circumstances, for end-to-end testing, you'll want to use @playwright/test (Playwright Test), and not playwright (Playwright Library) directly. To get started with Playwright Test, follow the Getting Started Guide.

使用库时的差异

¥Differences when using library

库示例

¥Library Example

以下是直接使用 Playwright Library 启动 Chromium、转到页面并检查其标题的示例:

¥The following is an example of using the Playwright Library directly to launch Chromium, go to a page, and check its title:

import { chromium, devices } from 'playwright';
import assert from 'node:assert';

(async () => {
// Setup
const browser = await chromium.launch();
const context = await browser.newContext(devices['iPhone 11']);
const page = await context.newPage();

// The actual interesting bit
await context.route('**.jpg', route => route.abort());
await page.goto('https://example.com/');

assert(await page.title() === 'Example Domain'); // 👎 not a Web First assertion

// Teardown
await context.close();
await browser.close();
})();

使用 node my-script.js 运行它。

¥Run it with node my-script.js.

测试实例

¥Test Example

实现类似行为的测试如下所示:

¥A test to achieve similar behavior, would look like:

import { expect, test, devices } from '@playwright/test';

test.use(devices['iPhone 11']);

test('should be titled', async ({ page, context }) => {
await context.route('**.jpg', route => route.abort());
await page.goto('https://example.com/');

await expect(page).toHaveTitle('Example');
});

使用 npx playwright test 运行它。

¥Run it with npx playwright test.

主要差异

¥Key Differences

需要注意的主要区别如下:

¥The key differences to note are as follows:

测试
安装npm install playwrightnpm init playwright@latest - 注意 installinit
安装浏览器安装 @playwright/browser-chromium@playwright/browser-firefox 和/或 @playwright/browser-webkitnpx playwright installnpx playwright install chromium 为单个
import 来自playwright@playwright/test
初始化明确需要:
  1. Pick a browser to use, e.g. chromium
  2. Launch browser with browserType.launch()
  3. Create a context with browser.newContext(), and pass any context options explicitly, e.g. devices['iPhone 11']
  4. Create a page with browserContext.newPage()
为每个开箱即用的测试提供隔离的 pagecontext,以及其他 内置夹具。没有显式的创建。如果测试在其参数中引用,则测试运行器将为测试创建它们。(即延迟初始化)
断言没有内置的 Web 优先断言Web 优先断言 喜欢: 自动等待并重试以满足条件。
清理明确需要:
  1. Close context with browserContext.close()
  2. Close browser with browser.close()
没有明确关闭 内置夹具;测试运行器会处理它。
运行使用库时,你可以将代码作为节点脚本运行,可能首先进行一些编译。使用测试运行程序时,你可以使用 npx playwright test 命令。测试运行程序与 config 一起处理所有编译并选择运行内容以及运行方式。

除上述内容外,Playwright Test 作为一个功能齐全的测试运行程序,还包括:

¥In addition to the above, Playwright Test, as a full-featured Test Runner, includes:

用法

¥Usage

使用 npm 或 Yarn 在 Node.js 项目中安装 Playwright 库。参见 系统要求

¥Use npm or Yarn to install Playwright library in your Node.js project. See system requirements.

npm i -D playwright

你还需要安装浏览器 - 手动或添加一个可以自动为你完成此操作的包。

¥You will also need to install browsers - either manually or by adding a package that will do it for you automatically.

# Download the Chromium, Firefox and WebKit browser
npx playwright install chromium firefox webkit

# Alternatively, add packages that will download a browser upon npm install
npm i -D @playwright/browser-chromium @playwright/browser-firefox @playwright/browser-webkit

有关更多选项,请参阅 管理浏览器

¥See managing browsers for more options.

安装后,你可以在 Node.js 脚本中导入 Playwright,并启动 3 个浏览器(chromiumfirefoxwebkit)中的任意一个。

¥Once installed, you can import Playwright in a Node.js script, and launch any of the 3 browsers (chromium, firefox and webkit).

const { chromium } = require('playwright');

(async () => {
const browser = await chromium.launch();
// Create pages, interact with UI elements, assert values
await browser.close();
})();

Playwright API 是异步的并返回 Promise 对象。我们的代码示例使用 异步/等待模式 来简化可读性。该代码封装在一个未命名的异步箭头函数中,该函数正在调用自身。

¥Playwright APIs are asynchronous and return Promise objects. Our code examples use the async/await pattern to ease readability. The code is wrapped in an unnamed async arrow function which is invoking itself.

(async () => { // Start of async arrow function
// Function code
// ...
})(); // End of the function and () to invoke itself

第一个脚本

¥First script

在我们的第一个脚本中,我们将导航到 https://playwright.nodejs.cn/ 并在 WebKit 中截取屏幕截图。

¥In our first script, we will navigate to https://playwright.nodejs.cn/ and take a screenshot in WebKit.

const { webkit } = require('playwright');

(async () => {
const browser = await webkit.launch();
const page = await browser.newPage();
await page.goto('https://playwright.nodejs.cn/');
await page.screenshot({ path: `example.png` });
await browser.close();
})();

默认情况下,Playwright 以无头模式运行浏览器。要查看浏览器 UI,请在启动浏览器时传递 headless: false 标志。你还可以使用 slowMo 来减慢执行速度。在调试工具 section 中了解更多信息。

¥By default, Playwright runs the browsers in headless mode. To see the browser UI, pass the headless: false flag while launching the browser. You can also use slowMo to slow down execution. Learn more in the debugging tools section.

firefox.launch({ headless: false, slowMo: 50 });

录制脚本

¥Record scripts

命令行工具 可用于记录用户交互并生成 JavaScript 代码。

¥Command line tools can be used to record user interactions and generate JavaScript code.

npx playwright codegen wikipedia.org

浏览器下载

¥Browser downloads

要下载 Playwright 浏览器,请运行:

¥To download Playwright browsers run:

# Explicitly download browsers
npx playwright install

或者,你可以添加 @playwright/browser-chromium@playwright/browser-firefox@playwright/browser-webkit 软件包,以便在软件包安装过程中自动下载相应的浏览器。

¥Alternatively, you can add @playwright/browser-chromium, @playwright/browser-firefox and @playwright/browser-webkit packages to automatically download the respective browser during the package installation.

# Use a helper package that downloads a browser on npm install
npm install @playwright/browser-chromium

在防火墙或代理后面下载

¥Download behind a firewall or a proxy

传递 HTTPS_PROXY 环境变量以通过代理下载。

¥Pass HTTPS_PROXY environment variable to download through a proxy.

# Manual
HTTPS_PROXY=https://192.0.2.1 npx playwright install

# Through @playwright/browser-chromium, @playwright/browser-firefox
# and @playwright/browser-webkit helper packages
HTTPS_PROXY=https://192.0.2.1 npm install

从工件存储库下载

¥Download from artifact repository

默认情况下,Playwright 从 Microsoft 的 CDN 下载浏览器。传递 PLAYWRIGHT_DOWNLOAD_HOST 环境变量以从内部工件存储库下载。

¥By default, Playwright downloads browsers from Microsoft's CDN. Pass PLAYWRIGHT_DOWNLOAD_HOST environment variable to download from an internal artifacts repository instead.

# Manual
PLAYWRIGHT_DOWNLOAD_HOST=192.0.2.1 npx playwright install

# Through @playwright/browser-chromium, @playwright/browser-firefox
# and @playwright/browser-webkit helper packages
PLAYWRIGHT_DOWNLOAD_HOST=192.0.2.1 npm install

跳过浏览器下载

¥Skip browser download

在某些情况下,希望完全避免浏览器下载,因为浏览器二进制文件是单独管理的。这可以通过在安装软件包之前设置 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD 变量来完成。

¥In certain cases, it is desired to avoid browser downloads altogether because browser binaries are managed separately. This can be done by setting PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD variable before installing packages.

# When using @playwright/browser-chromium, @playwright/browser-firefox
# and @playwright/browser-webkit helper packages
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install

TypeScript 支持

¥TypeScript support

Playwright 包含对 TypeScript 的内置支持。类型定义将自动导入。建议使用类型检查来改善 IDE 体验。

¥Playwright includes built-in support for TypeScript. Type definitions will be imported automatically. It is recommended to use type-checking to improve the IDE experience.

在 JavaScript 中

¥In JavaScript

将以下内容添加到 JavaScript 文件的顶部,以在 VS Code 或 WebStorm 中进行类型检查。

¥Add the following to the top of your JavaScript file to get type-checking in VS Code or WebStorm.

// @ts-check
// ...

或者,你可以使用 JSDoc 设置变量的类型。

¥Alternatively, you can use JSDoc to set types for variables.

/** @type {import('playwright').Page} */
let page;

在 TypeScript 中

¥In TypeScript

TypeScript 支持开箱即用。类型也可以显式导入。

¥TypeScript support will work out-of-the-box. Types can also be imported explicitly.

let page: import('playwright').Page;