跳到主要内容

Playwright Library

Playwright 模块提供了启动浏览器实例的方法。以下是使用 Playwright 进行自动化测试的典型示例:

const { chromium, firefox, webkit } = require('playwright');

(async () => {
const browser = await chromium.launch(); // 或者使用 'firefox' 或 'webkit'
const page = await browser.newPage();
await page.goto('http://example.com');
// 其他操作...
await browser.close();
})();

属性

chromium

Added before v1.9 playwright.chromium

该对象可用于启动或连接 Chromium 浏览器,返回 Browser 实例。

用法

playwright.chromium

类型


devices

Added before v1.9 playwright.devices

返回一个设备字典,可与 browser.newContext()browser.newPage() 一起使用。

const { webkit, devices } = require('playwright');
const iPhone = devices['iPhone 6'];

(async () => {
const browser = await webkit.launch();
const context = await browser.newContext({
...iPhone
});
const page = await context.newPage();
await page.goto('http://example.com');
// 其他操作...
await browser.close();
})();

用法

playwright.devices

类型


errors

Added before v1.9 playwright.errors

当 Playwright 方法无法完成请求时可能会抛出错误。例如,locator.waitFor() 如果在给定时间内选择器没有匹配到任何节点,就会失败。

对于特定类型的错误,Playwright 使用特定的错误类。这些类可以通过 playwright.errors 获取。

处理超时错误的示例:

try {
await page.locator('.foo').waitFor();
} catch (e) {
if (e instanceof playwright.errors.TimeoutError) {
// 如果是超时错误,执行某些操作
}
}

用法

playwright.errors

类型


firefox

Added before v1.9 playwright.firefox

此对象可用于启动或连接到 Firefox,返回 Browser 实例。

用法

playwright.firefox

类型


request

Added in: v1.16 playwright.request

暴露可用于 Web API 测试的 API。

用法

playwright.request

类型


selectors

Added before v1.9 playwright.selectors

选择器可用于安装自定义选择器引擎。更多信息请参阅 extensibility

用法

playwright.selectors

类型


webkit

v1.9 版本前添加 playwright.webkit

该对象可用于启动或连接到 WebKit,返回 Browser 实例。

用法

playwright.webkit

类型