Playwright 可以监听网页中发生的各种事件,例如网络请求、子页面创建、专用 Worker 创建等。订阅这些事件有多种方式:可以等待某个事件发生,也可以添加或移除事件监听器。
大多数情况下,脚本需要等待某个特定事件发生。下面是一些常见的事件等待模式。
使用 page.waitForRequest() 等待指定 URL 的请求:
// 在 goto 之前开始等待请求。注意这里没有 await。const requestPromise = page.waitForRequest('**/*logo*.png');await page.goto('https://wikipedia.org');const request = await requestPromise;console.log(request.url());等待弹出窗口:
// 在点击之前开始等待 popup。注意这里没有 await。const popupPromise = page.waitForEvent('popup');await page.getByText('open the popup').click();const popup = await popupPromise;await popup.goto('https://wikipedia.org');添加/移除事件监听器
Section titled “添加/移除事件监听器”有时事件会在随机时间发生,此时与其等待事件,不如直接处理事件。Playwright 支持使用常见的语言机制来订阅和取消订阅事件:
page.on('request', request => console.log(`Request sent: ${request.url()}`));
const listener = request => console.log(`Request finished: ${request.url()}`);page.on('requestfinished', listener);await page.goto('https://wikipedia.org');
page.off('requestfinished', listener);await page.goto('https://www.openstreetmap.org/');添加一次性监听器
Section titled “添加一次性监听器”如果某个事件只需要处理一次,可以使用便捷的一次性监听 API:
page.once('dialog', dialog => dialog.accept('2021'));await page.evaluate("prompt('Enter a number:')");