前言
页面上一闪而过的提示语,一般出现1-3秒就会消失,这种消息框如何定位呢?
示例
如下操作成功的提示语
它过1-3秒就自动消失了,按下f12, 鼠标还没指上去就不见了,无法获取它的元素属性。
误区: 首先这不是标准的alert,所以不能用 dialog 事件监听(很多初学者分不清alert 和弹出消息框)
调试暂停
F12后点开源代码,然后点暂停按钮
这时候页面处于调试暂停状态了
再回到检测元素,鼠标指上去,就能看到元素属性了
代码示例
断言消息框内容,可以直接用expect 断言
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=False, slow_mo=2000)
context = browser.new_context()
page = context.new_page()
page.goto('file:///C:/Users/dell/Desktop/a2/t.html')
# 点击success按钮
page.locator('.btn-success').click()
# 断言
expect(page.locator('.toast-message')).to_have_text("操作成功!")
page.pause()
有些同学习惯于先获取内容,再用assert 断言也可以
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=False, slow_mo=2000)
context = browser.new_context()
page = context.new_page()
page.goto('file:///C:/Users/dell/Desktop/a2/t.html')
# 点击success按钮
page.locator('.btn-success').click()
# 获取一闪而过的消息框内容
t = page.locator('.toast-message').inner_text()
print(f"消息框内容: {t}")
assert t == '操作成功!'
还有同学提到说如何判断消息框弹出来了, 用if判断元素is_visible() 即可
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=False, slow_mo=2000)
context = browser.new_context()
page = context.new_page()
page.goto('file:///C:/Users/dell/Desktop/a2/t.html')
# 点击success按钮
page.locator('.btn-success').click()
# 如何判断消息框弹出来了
if page.locator('.toast-message').is_visible():
print("消息框弹出来了。。。。")
page.pause()
标签:playwright,success,python,sync,context,70,new,page
From: https://www.cnblogs.com/yoyoketang/p/17636715.html