How to capture console logs using Playwright?

Playwright is a powerful tool for automating web browsers, and it provides an easy way to capture console logs from a webpage.

Here's how you can do it:

Python

In Python, you can use the Page.on("console") method to listen for console log events. Here's an example:

from playwright.sync_api import sync_playwright

def log(msg):
    print(msg.text)

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

    page.on("console", log)
    page.goto("https://example.com")
    browser.close()

In this example, log is a handler function that gets called whenever a console event occurs. The msg.text property contains the log message.

JavaScript

In JavaScript, you can use the page.on('console', msg => {...}) method to listen for console log events:

const playwright = require('playwright');

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

  page.on('console', msg => {
    for (let i = 0; i < msg.args.length; ++i)
      console.log(`${i}: ${msg.args[i]}`);
  });

  await page.goto('https://example.com');
  await browser.close();
})();

In this example, the callback function gets called whenever a console event occurs. The msg.args property contains the arguments of the log message.

Console Commands

There are no specific console commands for capturing console logs using Playwright. All the work is done in your Python or JavaScript code.

Remember to replace 'https://example.com' with the URL of the webpage you want to capture console logs from.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon