跳至主要内容

Library

简介

Playwright库提供了统一的API用于启动浏览器并进行交互,而Playwright Test在此基础上还提供了一个完全托管的端到端测试运行器及体验。

在大多数情况下,对于端到端测试,您会希望使用@playwright/test (Playwright Test),而不是直接使用playwright (Playwright Library)。要开始使用Playwright Test,请遵循Getting Started Guide

使用库时的差异

库示例

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

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 运行它。

测试示例

一个测试要实现类似的行为,看起来会像这样:

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 运行它。

主要差异

需要注意的关键区别如下:

LibraryTest
Installationnpm install playwrightnpm init playwright@latest - note install vs. init
Install browsersInstall @playwright/browser-chromium, @playwright/browser-firefox and/or @playwright/browser-webkitnpx playwright install or npx playwright install chromium for a single one
import fromplaywright@playwright/test
InitializationExplicitly need to:
  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. 使用 browserContext.newPage() 创建一个页面
An isolated page and context are provided to each test out-of the box, along with other built-in fixtures. No explicit creation. If referenced by the test in its arguments, the Test Runner will create them for the test. (i.e. lazy-initialization)
AssertionsNo built-in Web-First AssertionsWeb-First assertions like: which auto-wait and retry for the condition to be met.
TimeoutsDefaults to 30s for most operations.Most operations don't time out, but every test has a timeout that makes it fail (30s by default).
CleanupExplicitly need to:
  1. Close context with browserContext.close()
  2. 使用browser.close()关闭浏览器
No explicit close of built-in fixtures; the Test Runner will take care of it.
RunningWhen using the Library, you run the code as a node script, possibly with some compilation first.When using the Test Runner, you use the npx playwright test command. Along with your config, the Test Runner handles any compilation and choosing what to run and how to run it.

除了上述功能外,Playwright Test作为一个全功能的测试运行器还包括:

使用方法

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

npm i -D playwright

您还需要安装浏览器 - 可以手动安装,也可以通过添加一个能自动为您完成安装的软件包来实现。

# 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

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

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

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

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

Playwright API是异步的,返回Promise对象。我们的代码示例使用async/await模式来提高可读性。代码被包裹在一个立即调用的匿名异步箭头函数中。

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

第一个脚本

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

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

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

默认情况下,Playwright以无头模式运行浏览器。要查看浏览器界面,在启动浏览器时传入headless: false参数。您还可以使用slowMo来减慢执行速度。更多内容请参阅调试工具章节

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

录制脚本

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

npx playwright codegen wikipedia.org

浏览器下载

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

# Explicitly download browsers
npx playwright install

或者,您可以添加@playwright/browser-chromium@playwright/browser-firefox@playwright/browser-webkit包,以便在安装包时自动下载相应的浏览器。

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

在防火墙或代理服务器后下载

传递 HTTPS_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

从制品仓库下载

默认情况下,Playwright会从微软的CDN下载浏览器。可以通过设置PLAYWRIGHT_DOWNLOAD_HOST环境变量来改为从内部制品仓库下载。

# 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

跳过浏览器下载

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

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

TypeScript 支持

Playwright内置支持TypeScript。类型定义会自动导入。建议使用类型检查以提升IDE体验。

在JavaScript中

在您的JavaScript文件顶部添加以下内容,以便在VS Code或WebStorm中获得类型检查功能。

// @ts-check
// ...

或者,您可以使用JSDoc来为变量设置类型。

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

在TypeScript中

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

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