Skip to main content

Dialog

[对话] 对象通过页面的 [page.on("dialog")] 事件分发。

使用 Dialog 类的示例:

🌐 An example of using Dialog class:

from playwright.sync_api import sync_playwright, Playwright

def handle_dialog(dialog):
print(dialog.message)
dialog.dismiss()

def run(playwright: Playwright):
chromium = playwright.chromium
browser = chromium.launch()
page = browser.new_page()
page.on("dialog", handle_dialog)
page.evaluate("alert('1')")
browser.close()

with sync_playwright() as playwright:
run(playwright)
note

对话框会自动关闭,除非存在一个 page.on("dialog") 监听器。当存在监听器时,它 必须 要么 dialog.accept() 要么 dialog.dismiss() 对话框——否则页面将会因等待对话框而 冻结,点击等操作将永远无法完成。

🌐 Dialogs are dismissed automatically, unless there is a page.on("dialog") listener. When listener is present, it must either dialog.accept() or dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.


方法

🌐 Methods

accept

Added before v1.9 dialog.accept

当对话框被接受时返回。

🌐 Returns when the dialog has been accepted.

用法

dialog.accept()
dialog.accept(**kwargs)

参数

  • prompt_text str (optional)#

    要在提示中输入的文本。如果对话的 type 不是提示,则不会产生任何效果。可选。

返回


dismiss

Added before v1.9 dialog.dismiss

当对话框关闭时返回。

🌐 Returns when the dialog has been dismissed.

用法

dialog.dismiss()

返回


属性

🌐 Properties

default_value

Added before v1.9 dialog.default_value

如果对话是提示,则返回默认提示值。否则,返回空字符串。

🌐 If dialog is prompt, returns default prompt value. Otherwise, returns empty string.

用法

dialog.default_value

返回


message

Added before v1.9 dialog.message

对话框中显示一条消息。

🌐 A message displayed in the dialog.

用法

dialog.message

返回


page

Added in: v1.34 dialog.page

启动此对话框的页面(如果可用)。

🌐 The page that initiated this dialog, if available.

用法

dialog.page

返回


type

Added before v1.9 dialog.type

返回对话的类型,可以是 alertbeforeunloadconfirmprompt

🌐 Returns dialog's type, can be one of alert, beforeunload, confirm or prompt.

用法

dialog.type

返回