介绍
Playwright是一个Node.js库,通过单一API实现Chromium、Firefox和WebKit的自动化。Playwright的建立是为了实现跨浏览器的网络自动化,它是永远绿色的、有能力的、可靠的和快速的。
仓库:https://github.com/microsoft/playwright
官网:https://playwright.dev/
这是一个跨端的库,在windows、linux、macos,都可以使用。
如何安装请看完档。
例子
直接上例子: https://playwright.dev/docs/intro#first-test
import { test, expect } from '@playwright/test';import { chromium } from 'playwright'import path from "path"let all = [{"link": "https://baidu.com","title": "baidu"},]for (let item of all) {test(`save ${item.title}`, async () => {const web = await chromium.launch(// { headless: false } // 是否出现浏览器{proxy: {// server: 'socks5://127.0.0.1:1080', // 代理// username: 'usr',// password: 'pwd'}});const context = await web.newContext({javaScriptEnabled: false});const newpage = await context.newPage();await newpage.goto(`${item.link}`, {referer: "",// timeout: 30,waitUntil: "load"});await newpage.emulateMedia({ media: 'screen' });await newpage.pdf({ path: path.resolve(__dirname, `./pdf/${item.title}.pdf`) });})}
这是一个,将整个网页截图的脚本。
当然Playwright不止这么用,可以对网页应用进行跑在浏览器中的测试。
import { test, expect } from '@playwright/test';test('basic test', async ({ page }) => {await page.goto('https://playwright.dev/');const name = await page.innerText('.navbar__title');expect(name).toBe('Playwright');});
结尾
十分推荐这个测试,集成度很高,基本上浏览器应用想测试的部分都能测试的到。
我这个库HTMLParser 就使用到了playwright,来测试我解析的DOM结构和浏览器是否一致。

