Dialog对象
用来侦听对话框操作,alert,beforeunload(在文档即将被卸载之前发生此事件),confirm或prompt等
官方解释:Dialogs are dismissed automatically, unless there is a page.on(“dialog”) listener. When listener is present, it must either dialog.accept(**kwargs) or dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.
也就是说对话框如果没有page.on('dialog')
监听会自动消失,一旦有了监听事件,必须后面跟着dialog.accecpt(**kwargs)
和dialog.dismiss()
,否则对话框会一直停在点击事件,如下:
alert提示框:
from playwright.sync_api import sync_playwright
with sync_playwright() as sp:
browser = sp.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
# 代码实现
page.on('dialog', lambda dialog: print(dialog.message)) # hello playwright!
page.evaluate('alert("hello playwright!")')
context.close()
browser.close()
结果如下:
除非手动点击,否则会一直阻塞,加入dialog.accecpt(**kwargs)
和dialog.dismiss()
即可解决上述问题
from playwright.sync_api import sync_playwright
def handle_dialog(dialog):
print(dialog.message)
dialog.accept()
with sync_playwright() as sp:
browser = sp.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
# 代码实现
page.on('dialog', handle_dialog)
page.evaluate('alert("hello playwright!")')
context.close()
browser.close()
prompt提示框:
from playwright.sync_api import sync_playwright
def handle_dialog(dialog):
print(dialog.message, dialog.type, dialog.default_value)
dialog.accept(prompt_text='OK')
with sync_playwright() as sp:
browser = sp.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
# 代码实现
page.on('dialog', handle_dialog)
page.evaluate('prompt("hello playwright!","good idea")')
context.close()
browser.close()
prompt()有两个参数:
- text: 要在对话框中显示的纯文本
- defaultText: 默认的输入文本
上述使用了dialog.accept(prompt_text=‘OK’): [ prompt_text 官方解释: A text to enter in prompt. Does not cause any effects if the dialog’s type is not prompt. Optional.]不过并没有发现prompt_text参数对实际操作有什么影响
dialog.default_value
: 如果对话框是prompt,则其值为defaultText
dialog.message
: 对话框中显示的消息
dialog.type
: 对话框的类型,alert,beforeunload,confirm或prompt
confirm提示框可以自行演示
beforeunload提示框:
用脚本模拟的方式弹出beforeunload提示框:
from playwright.sync_api import Playwright, sync_playwright
def handle_dialog(dialog):
print(dialog.type)
dialog.dismiss()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
# Open new page
page = context.new_page()
page.goto("https://www.w3school.com.cn/tiy/t.asp?f=event_onbeforeunload")
# Click text=点击此处访问 w3school.com.cn
page.on("dialog", handle_dialog)
page.frame(name="iframeResult").click("text=点击此处访问 w3school.com.cn")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)