Tue. Mar 28th, 2023

A quick example of how to access the browser console when running automated tests in Python using Selenium.

As always lets first import web driver from the selenium module:

from selenium import webdriver

Specify a URL:

url = 'https://www.moneyhelper.org.uk'

Specify our browser web driver:

driver = webdriver.Safari()

Visit the url:

driver.get(url)

Store the browser console log into a new object:

browser_log = driver.get_log('browser')

This will return a list of dictionaries, first we’ll unpack the list and then the dictionaries within, and print out the contents of the log:

for log in browser_log:
    for key, value in log.items():
        print("\nKey: {key}\nValue: {value}".format(
            key=key,
            value=value
        ))

Then finally close the browser:

driver.close()

Putting it all together

from selenium import webdriver
driver = webdriver.Safari()
url = 'https://www.msn.com'
driver.get(url)
browser_log = driver.get_log('browser')
for log in browser_log:
    for key, value in log.items():
        print("\nKey: {key}\nValue: {value}".format(
            key=key,
            value=value
        ))

driver.close()

Output:

Key: level
Value: WARNING

Key: message
Value: security - Error with Permissions-Policy header: Invalid allowlist item(none) for feature geolocation. Allowlist item must be *, self or quoted url.

Key: source
Value: security

Key: timestamp
Value: 1674119338004

Key: level
Value: WARNING

Key: message
Value: security - Error with Permissions-Policy header: Invalid allowlist item(none) for feature microphone. Allowlist item must be *, self or quoted url.

Key: source
Value: SEVERE

Key: message
Value: https://www.moneyhelper.org.uk/en 5106:41 Uncaught ReferenceError: _satellite is not defined

Key: source
Value: javascript

Key: timestamp
Value: 1674119338399

Key: level
Value: SEVERE

Key: message
Value: https://assets.adobedtm.com/c3a3920a84ef/2104df5e2099/launch-a40370bb1e84.min.js - Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Key: source
Value: network

Key: timestamp
Value: 1674119338538

Detecting Severe issues

The severity level of one of the objects in the output is highlighted as ‘SEVERE’, you might want to raise an error in python as part of your tests.

To do this add the following if statement which checks the value unpacked from the log dictionaries:

for log in browser_log:
    for key, value in log.items():

        # NEW
        if value == 'SEVERE':
            raise ValueError(f'> Severe error found in console: {log}')

        print("\nKey: {key}\nValue: {value}".format(
            key=key,
            value=value
        ))

By admin