イベント
はじめに
Playwright は、ネットワークリクエスト、子ページの作成、専用ワーカーなど、Web ページ上で発生するさまざまなタイプのイベントをリッスンできます。イベントを待機したり、イベントリスナーを追加または削除するなど、このようなイベントをサブスクライブする方法はいくつかあります。
イベントを待つ
ほとんどの場合、スクリプトは特定のイベントが発生するのを待つ必要があります。以下に、一般的なイベント待機パターンをいくつか示します。
page.expect_request() を使用して、指定された URL のリクエストを待ちます
- 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:')")