事件
介绍
¥Introduction
Playwright 允许监听网页上发生的各种类型的事件,例如网络请求、子页面的创建、专用工作者等。有几种方法可以订阅此类事件,例如等待事件或添加或删除事件监听器。
¥Playwright allows listening to various types of events happening on the web page, such as network requests, creation of child pages, dedicated workers etc. There are several ways to subscribe to such events, such as waiting for events or adding or removing event listeners.
等待事件
¥Waiting for event
大多数时候,脚本需要等待特定事件的发生。以下是一些典型的事件等待模式。
¥Most of the time, scripts will need to wait for a particular event to happen. Below are some of the typical event awaiting patterns.
使用 Page.RunAndWaitForRequestAsync() 等待指定 url 的请求:
¥Wait for a request with the specified url using Page.RunAndWaitForRequestAsync():
var waitForRequestTask = page.WaitForRequestAsync("**/*logo*.png");
await page.GotoAsync("https://wikipedia.org");
var request = await waitForRequestTask;
Console.WriteLine(request.Url);
等待弹出窗口:
¥Wait for popup window:
var popup = await page.RunAndWaitForPopupAsync(async =>
{
await page.GetByText("open the popup").ClickAsync();
});
await popup.GotoAsync("https://wikipedia.org");
添加/删除事件监听器
¥Adding/removing event listener
有时,事件是随机发生的,我们不需要等待它们,而是需要对其进行处理。Playwright 支持订阅和取消订阅事件的传统语言机制:
¥Sometimes, events happen in random time and instead of waiting for them, they need to be handled. Playwright supports traditional language mechanisms for subscribing and unsubscribing from the events:
page.Request += (_, request) => Console.WriteLine("Request sent: " + request.Url);
void listener(object sender, IRequest request)
{
Console.WriteLine("Request finished: " + request.Url);
};
page.RequestFinished += listener;
await page.GotoAsync("https://wikipedia.org");
// Remove previously added listener.
page.RequestFinished -= listener;
await page.GotoAsync("https://www.openstreetmap.org/");