Capturing browser console logs helps find errors or warnings that happen on a webpage during testing.
0
0
Browser console log capture in Selenium Python
Introduction
When you want to check if any JavaScript errors appear on the page.
When you need to verify warnings or messages logged by the website.
When debugging why a page behaves unexpectedly during automated tests.
When tracking performance or security messages shown in the console.
When ensuring no unexpected errors occur after a user action.
Syntax
Selenium Python
logs = driver.get_log('browser')This command fetches all browser console logs collected so far.
It returns a list of log entries, each with a message and level (e.g., SEVERE, WARNING).
Examples
Fetch and print all console log entries.
Selenium Python
logs = driver.get_log('browser') for entry in logs: print(entry)
Filter and print only severe error messages from the console logs.
Selenium Python
error_logs = [log for log in driver.get_log('browser') if log['level'] == 'SEVERE'] print(error_logs)
Sample Program
This script opens a Chrome browser, navigates to example.com, captures all browser console logs, prints each log's level and message, then closes the browser.
Selenium Python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options options = Options() options.set_capability('goog:loggingPrefs', {'browser': 'ALL'}) service = Service() driver = webdriver.Chrome(service=service, options=options) try: driver.get('https://example.com') logs = driver.get_log('browser') for entry in logs: print(f"{entry['level']}: {entry['message']}") finally: driver.quit()
OutputSuccess
Important Notes
Make sure to enable logging preferences in browser options before starting the driver.
Not all browsers support console log capture equally; Chrome is commonly used for this.
Logs may include info, warnings, and errors; filter as needed for your test goals.
Summary
Browser console log capture helps find hidden errors during tests.
Use driver.get_log('browser') to get logs.
Filter logs by level to focus on important messages.