首页 / Playwright 入门教程 / 库模式 Library

Playwright 入门教程

库模式 Library

本教程共 59 篇 · 第 53 篇 · 更新于 2026-08-04 · 约 7 分钟阅读

Playwright库模式Library测试运行器脚本API对照何时使用

53. 库模式 Library

本节目标:学完你能分清「测试运行器」和「底层库」两种用法,知道啥时候该脱离测试运行器,直接拿库写脚本。

前面所有章节都靠测试运行器(Playwright Test)跑。但 Playwright 还有一层更底的东西——库(Library,包名就是 playwright)。它只管「启动浏览器、操作页面」,不带测试框架那套。

两套东西有啥不同

  • @playwright/test:测试运行器。自带并行、重试、报告、Fixture(夹具)、Web-First 断言,一条 npx playwright test 全包了。
  • playwright:底层库。只有浏览器 API,没有测试管理。你写个 Node 脚本,自己 node 跑。
Tip

绝大多数端到端测试,直接用 @playwright/test 就好。库模式是给「不是测试」的场景准备的。

库模式长啥样

直接用库启动 Chromium、拦截图片、检查标题:

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

(async () => {
  // 1. 自己启动浏览器
  const browser = await chromium.launch();
  // 2. 自己建上下文,顺手带设备模拟
  const context = await browser.newContext(devices['iPhone 11']);
  const page = await context.newPage();

  // 3. 真正的业务逻辑
  await context.route('**.jpg', route => route.abort());
  await page.goto('https://example.com/');
  assert(await page.title() === 'Example Domain'); // 👎 不是 Web-First 断言

  // 4. 自己关
  await context.close();
  await browser.close();
})();

跑它:node my-script.js。注意最后要手动 close,否则浏览器进程赖着不走。

对照:测试运行器版

同样的事用测试运行器写,省掉一大堆样板:

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

关键差别一览

维度库模式测试运行器
安装npm i playwrightnpm init playwright@latest
装浏览器@playwright/browser-chromiumnpx playwright install
导入from 'playwright'from '@playwright/test'
初始化自己 launch、建 context、建 page测试参数里直接拿到隔离好的 page
断言没有 Web-First 断言toHaveTitle 等,自动等
超时多数操作默认 30 秒测试整体有超时,自动失败
清理自己 close context 和 browser运行器自动收
运行node 脚本npx playwright test
Warning

库模式里没有 Web-First 断言。上面那个 assert 是 Node 自带的,不重试、不等元素。写库脚本要自己处理等待。

怎么装库

npm i -D playwright
npx playwright install chromium firefox webkit

也可以加自动下载浏览器的辅助包,免去手动 install

npm i -D @playwright/browser-chromium @playwright/browser-firefox @playwright/browser-webkit

第一个库脚本

比如用 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();
})();

想看浏览器界面,launch 时加 headless: false;想放慢看清楚,加 slowMo

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

什么时候该用库模式

适合「不是测试」的自动化:

  • 爬数据、批量生成截图。
  • 给别的系统做页面健康检查探针。
  • 在已有 Node 程序里嵌入浏览器操作。
  • 写工具脚本,不需要测试框架的报告和并行。

不适合:正经的功能回归测试。那种还是 @playwright/test 更省心。

一句话:库模式是「只要浏览器能力、不要测试框架」时的选择;写测试就老实用测试运行器。

小结

这章讲了库模式(playwright)和测试运行器(@playwright/test)的本质差别:库只管启动浏览器和操作页面,没测试框架那套。几个要记住的:库模式没 Web-First 断言,得自己手写等待;得手动 close 浏览器,不然进程赖着不走。它适合爬数据、批量截图、健康探针这类「不是测试」的场景。正经回归测试,测试运行器更省心。