How to capture console logs using Playwright?

Playwright provides a robust event-driven approach to capture console logs from web pages during automation. This capability is essential for debugging JavaScript applications and monitoring client-side behavior.

Basic Console Log Capture

Python

Use the page.on("console") event listener to capture all console messages:

from playwright.sync_api import sync_playwright

def handle_console_log(msg):
    print(f"Console {msg.type}: {msg.text}")

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

    page.on("console", handle_console_log)
    page.goto("https://example.com")

    browser.close()

JavaScript/Node.js

const { chromium } = require('playwright');

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

  page.on('console', msg => {
    console.log(`Console ${msg.type()}: ${msg.text()}`);
  });

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

Advanced Console Log Handling

Filtering by Log Level

Capture only specific types of console messages:

from playwright.sync_api import sync_playwright

def handle_console_log(msg):
    if msg.type == "error":
        print(f"ERROR: {msg.text}")
    elif msg.type == "warning":
        print(f"WARNING: {msg.text}")
    elif msg.type == "log":
        print(f"INFO: {msg.text}")

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

    page.on("console", handle_console_log)
    page.goto("https://example.com")

    browser.close()

Storing Console Logs

Collect console logs in a list for later analysis:

from playwright.sync_api import sync_playwright

console_logs = []

def collect_console_log(msg):
    console_logs.append({
        'type': msg.type,
        'text': msg.text,
        'location': msg.location
    })

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

    page.on("console", collect_console_log)
    page.goto("https://example.com")

    # Analyze collected logs
    for log in console_logs:
        print(f"{log['type'].upper()}: {log['text']}")

    browser.close()

JavaScript with Detailed Message Handling

const { chromium } = require('playwright');

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

  const consoleLogs = [];

  page.on('console', async msg => {
    const values = [];
    for (const arg of msg.args()) {
      values.push(await arg.jsonValue());
    }

    consoleLogs.push({
      type: msg.type(),
      text: msg.text(),
      args: values,
      location: msg.location()
    });
  });

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

  // Print collected logs
  consoleLogs.forEach(log => {
    console.log(`${log.type.toUpperCase()}: ${log.text}`);
    if (log.location) {
      console.log(`  at ${log.location.url}:${log.location.lineNumber}`);
    }
  });

  await browser.close();
})();

Async Context (Python)

For async Python applications:

import asyncio
from playwright.async_api import async_playwright

async def handle_console_log(msg):
    print(f"Console {msg.type}: {msg.text}")

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        page.on("console", handle_console_log)
        await page.goto("https://example.com")

        await browser.close()

asyncio.run(main())

Console Message Properties

Console messages in Playwright provide several useful properties:

  • msg.type: Log level ("log", "error", "warning", "info", "debug")
  • msg.text: Complete message text
  • msg.args: Array of console arguments
  • msg.location: Source location (file, line number) where the log occurred

Common Use Cases

  1. Debugging JavaScript errors during automated testing
  2. Monitoring API calls logged by the frontend
  3. Tracking user interactions via console.log statements
  4. Capturing performance metrics logged to the console
  5. Validating expected log messages in test scenarios

Best Practices

  • Set up console listeners before navigating to the page
  • Filter logs by type to focus on relevant messages
  • Store logs with timestamps for debugging sequence issues
  • Handle both synchronous and asynchronous logging scenarios
  • Consider using structured logging formats for easier parsing

Remember to replace 'https://example.com' with your target webpage URL. Console log capture works across all Playwright-supported browsers (Chromium, Firefox, Safari).

Related Questions

Get Started Now

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