page.on('dialog')
playwright 框架可以监听dialog事件,不管你alert 什么时候弹出来,监听到事件就自动处理了。
当出现 JavaScript 对话框时发出,例如alert、prompt或。侦听器必须dialog.accept()或dialog.dismiss()对话框 - 否则页面将冻结等待对话框,并且单击等操作将永远不会完成。
page.on("dialog", handler)
from playwright.sync_api import sync_playwright
def handle_dialog(dialog):
print(dialog.message)
dialog.dismiss()
def run(playwright):
chromium = playwright.chromium
browser = chromium.launch(headless=False,slow_mo=1000)
page = browser.new_page()
page.goto("http://www.baidu.com")
page.on("dialog", handle_dialog)
page.evaluate("alert('1')")
browser.close()
with sync_playwright() as playwright:
run(playwright)
示例:
html页面如下
<!DOCTYPE html>
<html>
<head>
<title>Confirm Dialog Example</title>
</head>
<body>
<h1>Confirm Dialog Example</h1>
<p>Click the button below to display a confirm dialog:</p>
<button onclick="displayConfirm()">Click Me</button>
<script>
function displayConfirm() {
var result = confirm("Are you sure you want to delete this item?");
if (result) {
alert("Item deleted successfully");
} else {
alert("Delete cancelled");
}
}
</script>
</body>
</html>
如下代码打开html页面,点击click me按钮,并接受confirm弹框,因为运行太快,我这里生成了一个trace文件,可以查看执行过程
from playwright.sync_api import sync_playwright, Dialog
def handle_dialog(dialog:Dialog):
print(dialog.message)
dialog.accept()
def run(playwright):
chromium = playwright.chromium
browser = chromium.launch(headless=False)
context = browser.new_context()
context.tracing.start(screenshots=True, snapshots=True, sources=True)
page = context.new_page()
page.goto(r"C:\log.html")
page.get_by_text("Click Me").click()
page.on("dialog", handle_dialog)
context.tracing.stop(path="trace.zip")
browser.close()
with sync_playwright() as playwright:
run(playwright)
由trace view可以看到,自动执行了两次dialog.dismiss
即使handle_dialog方法里什么都不写,有监听事件,也会自动执行dislog.dismiss。
方法
accept()
dialog.accept()
dialog.accept(**kwargs)
dismiss()
在对话框关闭时返回。
dialog.dismiss()
属性
default_value
如果对话框为提示,则返回默认提示值。否则,返回空字符串。
dialog.default_value
message
对话框中显示的消息。
dialog.message
page
启动此对话框的页面(如果可用)。
dialog.page
type
返回对话框类型alert、
beforeunload、
confirm、
prompt
dialog.type