在 Robotframework 中使用浏览器库时如何获取浏览器控制台日志

How to get browser console logs when using Browser library in Robotframework

我正在使用 Robotframework 和浏览器库来自动执行网络上的一些任务。我曾经使用 Selenium,并且使用 selenium 有一种获取日志的方法,例如在失败的情况下:

driver = webdriver.Remote()
logs = driver.get_log('browser')

我一直在努力寻找一种方法来使用 Playwright 的浏览器库来完成同样的事情。可能吗?

当然可以。您可以使用 page.on('console') event to log what appears in the DevTools console. Here's an example of using debug 库来执行此操作。

确保 export DEBUG=playwright:console 否则您将看不到任何内容。 以下是在 JS 中的实现方法:

const playwright = require('playwright');
const debugConsole = require('debug')('playwright:console');

(async () => {
    const browser = await playwright.chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();

    await page.on('console', (msg) => {
        if (msg && msg.text) {
          if (typeof msg.text === 'function') {
            debugConsole('PAGE LOG:', msg.text());
          } else {
            debugConsole('PAGE LOG:', msg.text);
          }
        } else {
          debugConsole('PAGE LOG:', msg);
        }
    });

    await page.goto('https://example.com', { waitUntil: 'networkidle' });

})();

在python中:

from playwright.sync_api import sync_playwright

def print_args(msg):
    for arg in msg.args:
        print(arg.json_value())

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.on("console", print_args)
    page.goto("https://abrahamjuliot.github.io/creepjs/", wait_until="networkidle")
    page.wait_for_timeout(5000)
    browser.close()

如果您正在寻找更多 system-level 内容,您还可以设置一个 dumpio 启动参数,这将导致 Playwright 在实际启动浏览器可执行文件时提供详细的日志。