Skip to main content

对话框

介绍

🌐 Introduction

Playwright 可以与网页对话框进行交互,例如 alertconfirmprompt 以及 beforeunload 确认框。有关打印对话框,请参见 Print

🌐 Playwright can interact with the web page dialogs such as alert, confirm, prompt as well as beforeunload confirmation. For print dialogs, see Print.

alert(), confirm(), prompt() 对话框

🌐 alert(), confirm(), prompt() dialogs

默认情况下,Playwright 会自动关闭对话框,因此你无需手动处理它们。不过,你可以在触发对话框的操作之前注册一个对话框处理程序,以选择 dialog.accept()dialog.dismiss() 对其进行处理。

🌐 By default, dialogs are auto-dismissed by Playwright, so you don't have to handle them. However, you can register a dialog handler before the action that triggers the dialog to either dialog.accept() or dialog.dismiss() it.

page.on("dialog", lambda dialog: dialog.accept())
page.get_by_role("button").click()
note

page.on("dialog") 监听器必须处理对话框。否则你的操作会被阻塞,无论是 locator.click() 还是其他操作。这是因为网页中的对话框是模态的,因此在处理之前会阻塞页面的进一步执行。

因此,以下代码片段将永远无法解析:

🌐 As a result, the following snippet will never resolve:

warning

错误!

🌐 WRONG!

page.on("dialog", lambda dialog: print(dialog.message))
page.get_by_role("button").click() # Will hang here
note

如果没有为 [page.on("dialog")] 设置监听器,所有对话框都会被自动关闭。

🌐 If there is no listener for page.on("dialog"), all dialogs are automatically dismissed.

卸载前对话框

🌐 beforeunload dialog

当使用为真值的 run_before_unload 调用 page.close() 时,页面会执行其卸载处理程序。这是 page.close() 唯一不等待页面实际关闭的情况,因为在操作结束时页面可能仍然保持打开状态。

🌐 When page.close() is invoked with the truthy run_before_unload value, the page runs its unload handlers. This is the only case when page.close() does not wait for the page to actually close, because it might be that the page stays open in the end of the operation.

你可以注册一个对话处理程序来自行处理 beforeunload 对话:

🌐 You can register a dialog handler to handle the beforeunload dialog yourself:

def handle_dialog(dialog):
assert dialog.type == 'beforeunload'
dialog.dismiss()

page.on('dialog', lambda: handle_dialog)
page.close(run_before_unload=True)

🌐 Print dialogs

为了断言通过 window.print 触发了打印对话框,你可以使用以下代码片段:

🌐 In order to assert that a print dialog via window.print was triggered, you can use the following snippet:

page.goto("<url>")

page.evaluate("(() => {window.waitForPrintDialog = new Promise(f => window.print = f);})()")
page.get_by_text("Print it!").click()

page.wait_for_function("window.waitForPrintDialog")

这将等待在按钮被点击后打印对话框打开。确保在点击按钮或页面加载后评估脚本。

🌐 This will wait for the print dialog to be opened after the button is clicked. Make sure to evaluate the script before clicking the button / after the page is loaded.