ConsoleMessage
页面在触发 page.on("console") 事件时会生成 ConsoleMessage 对象。页面中每一次 console.* 调用都会在 Playwright 中对应一个事件。
- Sync
- Async
# 监听全部 console 日志
page.on("console", lambda msg: print(msg.text))
# 监听全部 console 事件,但只处理 error
page.on("console", lambda msg: print(f"error: {msg.text}") if msg.type == "error" else None)
# 等待下一条 console 输出
with page.expect_console_message() as msg_info:
# 在页面里调用 console.log
page.evaluate("console.log('hello', 42, { foo: 'bar' })")
msg = msg_info.value
# 解析打印的各个参数
msg.args[0].json_value() # hello
msg.args[1].json_value() # 42
# 监听全部 console 日志
page.on("console", lambda msg: print(msg.text))
# 监听全部 console 事件,但只处理 error
page.on("console", lambda msg: print(f"error: {msg.text}") if msg.type == "error" else None)
# 等待下一条 console 输出
async with page.expect_console_message() as msg_info:
await page.evaluate("console.log('hello', 42, { foo: 'bar' })")
msg = await msg_info.value
# 解析打印的各个参数
await msg.args[0].json_value() # hello
await msg.args[1].json_value() # 42
console_message.args
Added in: v1.8返回调用 console.* 时传入的参数列表,可结合 page.on("console") 一起处理。
console_message.location
Added in: v1.8console_message.text
Added in: v1.8获取 console 消息的纯文本。
console_message.type
Added in: v1.8可能的类型包括:log、debug、info、error、warning、dir、dirxml、table、trace、clear、startGroup、startGroupCollapsed、endGroup、assert、profile、profileEnd、count、timeEnd。