事件
簡介
Playwright 允許監聽網頁上發生的各種類型事件,例如網路請求、子頁面的建立、專用工作者等。有幾種方式可以訂閱此類事件,例如等待事件或添加或移除事件監聽器。
等待事件
大多數情況下,腳本需要等待特定事件發生。以下是一些典型的事件等待模式。
等待具有指定 url 的請求,使用 page.expect_request():
- Sync
- Async
with page.expect_request("**/*logo*.png") as first:
page.goto("https://wikipedia.org")
print(first.value.url)
async with page.expect_request("**/*logo*.png") as first:
await page.goto("https://wikipedia.org")
first_request = await first.value
print(first_request.url)
等待彈出視窗:
- Sync
- Async
with page.expect_popup() as popup:
page.get_by_text("open the popup").click()
popup.value.goto("https://wikipedia.org")
async with page.expect_popup() as popup:
await page.get_by_text("open the popup").click()
child_page = await popup.value
await child_page.goto("https://wikipedia.org")
添加/移除事件監聽器
有時,事件會隨機發生,與其等待它們,不如處理它們。Playwright 支援傳統語言機制來訂閱和取消訂閱事件:
- Sync
- Async
def print_request_sent(request):
print("Request sent: " + request.url)
def print_request_finished(request):
print("Request finished: " + request.url)
page.on("request", print_request_sent)
page.on("requestfinished", print_request_finished)
page.goto("https://wikipedia.org")
page.remove_listener("requestfinished", print_request_finished)
page.goto("https://www.openstreetmap.org/")
def print_request_sent(request):
print("Request sent: " + request.url)
def print_request_finished(request):
print("Request finished: " + request.url)
page.on("request", print_request_sent)
page.on("requestfinished", print_request_finished)
await page.goto("https://wikipedia.org")
page.remove_listener("requestfinished", print_request_finished)
await page.goto("https://www.openstreetmap.org/")
添加一次性監聽器
如果某個事件需要處理一次,有一個方便的 API 可以使用:
- Sync
- Async
page.once("dialog", lambda dialog: dialog.accept("2021"))
page.evaluate("prompt('Enter a number:')")
page.once("dialog", lambda dialog: dialog.accept("2021"))
await page.evaluate("prompt('Enter a number:')")