Accessing the DataLayer in Selenium using Python

An easy example of storing and returning the contents of a site data layer in Selenium and Python.

# Import webdriver from selenium
from selenium import webdriver

# Specify our target URL
url = 'https://www.moneyhelper.org.uk'

# Specify the driver
DRIVER_BIN = "Webdrivers\msedgedriver.exe"
driver = webdriver.Edge(executable_path=DRIVER_BIN)

# Launch the browser and visit the URL
driver.get(url)

# Get the datalayer
datalayer = driver.execute_script("return window.dataLayer")

# Print the items in the Datalayer
for item in datalayer:
    print(item)

driver.close()

Output:

['consent', 'default', {'ad_storage': 'denied', 'analytics_storage': 'denied'}]
{'event': 'default_consent'}
{'event': 'gtm.js', 'gtm.start': 1674127499016}

Posted

in

,

by

Tags: