playwright如何处理网页弹框

游客 发布于 2023-12-07 阅读(34)
在Playwright中,处理网页弹框通常涉及两种主要类型的对话框:alert, confirm 和 prompt。这些对话框可以通过页面上的JavaScript代码触发。你可以使用Playwright提供的方法来监听和操作这些对话框。

以下是如何使用Playwright处理这三种不同类型的对话框:

Alert:

当一个alert对话框出现时,可以使用page.on("dialog")事件处理器来捕获它。

然后调用dialog.accept()来接受对话框,或者dialog.dismiss()来拒绝(关闭)对话框。

python

from playwright.sync_api import sync_playwright

def run(playwright):

with playwright.chromium.launch(headless=False) as browser:

context = browser.new_context()

page = context.new_page()

# 监听 alert 对话框

page.on("dialog", lambda dialog: dialog.accept())

page.goto("http://example.com")

page.evaluate("alert('Hello, world!')")

context.close()

with sync_playwright() as playwright:

run(playwright)

Confirm:

处理confirm对话框与处理alert对话框类似,但你需要检查对话框的内容以确定它是哪种类型的对话框。

使用dialog.accept()或dialog.dismiss()来决定是否接受确认请求。

python

from playwright.sync_api import sync_playwright

def run(playwright):

with playwright.chromium.launch(headless=False) as browser:

context = browser.new_context()

page = context.new_page()

def on_dialog(dialog):

if "Do you want to confirm?" in dialog.message():

dialog.accept()

else:

dialog.dismiss()

# 监听所有对话框

page.on("dialog", on_dialog)

page.goto("http://example.com")

page.evaluate("confirm('Do you want to confirm?')")

context.close()

with sync_playwright() as playwright:

run(playwright)

Prompt:

处理prompt对话框需要提供一个输入值,因为它们通常要求用户提供一些信息。

你可以在对话框上调用dialog.accept(value)或dialog.dismiss(),其中value是要传递给对话框的输入值。

python

from playwright.sync_api import sync_playwright

def run(playwright):

with playwright.chromium.launch(headless=False) as browser:

context = browser.new_context()

page = context.new_page()

def on_dialog(dialog):

if dialog.type == "prompt":

dialog.accept("Input value goes here.")

else:

dialog.dismiss()

# 监听所有对话框

page.on("dialog", on_dialog)

page.goto("http://example.com")

page.evaluate("prompt('Please enter your name:', 'John Doe')")

context.close()

with sync_playwright() as playwright:

run(playwright)

请注意,上述示例使用了同步API。如果你想要使用异步API,只需将所有的sync_前缀替换为async_,并在适当的地方使用await关键字。