Capturing Console Logs using Selenium Python
Capturing browser console logs during Selenium test execution can be extremely helpful for debugging front-end issues such as JavaScript errors, failed API calls, or warnings that occur during runtime. Selenium WebDriver in Python allows you to access these logs, particularly when using ChromeDriver or EdgeDriver (as they are based on Chromium).
✅ Why Capture Console Logs?
Identify JavaScript errors affecting UI behavior
Debug network issues or blocked resources
Validate that no unexpected warnings are triggered during test execution
Ensure front-end best practices are followed
π ️ Prerequisites
Python 3.x
Selenium installed (pip install selenium)
Chrome browser and ChromeDriver installed (ensure versions match)
⚙️ Setting Up Logging Preferences
To capture console logs, you need to enable logging via Chrome options and desired capabilities.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# Enable browser logging
caps = DesiredCapabilities.CHROME.copy()
caps['goog:loggingPrefs'] = {'browser': 'ALL'}
options = webdriver.ChromeOptions()
service = Service("path/to/chromedriver")
driver = webdriver.Chrome(service=service, desired_capabilities=caps, options=options)
π Accessing Console Logs
Once your test has run or at a desired checkpoint, use the following to fetch console logs:
# Navigate to page
driver.get("https://example.com")
# Capture browser console logs
logs = driver.get_log("browser")
for entry in logs:
print(f"{entry['level']} - {entry['message']}")
Log levels include:
INFO
WARNING
SEVERE (typically JavaScript errors)
π Sample Output
SEVERE - https://example.com/script.js 404 (Not Found)
WARNING - [Deprecation] Something is deprecated
INFO - Console message from script.js
π« Limitations
Not supported in Firefox directly via Selenium
Logs may not include network-level details (use browser devtools protocol or tools like BrowserMob Proxy for that)
Works only with Chromium-based browsers
✅ Pro Tip: Filter Logs for Errors Only
errors = [log for log in logs if log['level'] == 'SEVERE']
if errors:
print("JavaScript errors found:")
for error in errors:
print(error['message'])
π Final Thoughts
Capturing console logs with Selenium Python is a powerful debugging tool that helps bridge the gap between UI automation and front-end validation. It enables you to detect silent failures in scripts and browser behavior that traditional test assertions might miss. Add it to your automation suite for more robust and reliable testing.
Learn Selenium with Pyhton Training Hyderabad
Read More: Debugging Selenium Python Scripts
Read More: Advanced XPath Techniques in Selenium Python
Read More: Organizing Large Selenium Python Projects
Visit IHUB Talent Institute Hyderabad
Get Direction
Comments
Post a Comment