Local Storage with selenium

Feb 23, 2021 code

TL;DR

Here is a quick way to add local storage for any website that is storing tokens inside local storage using python and selenium.

from selenium import webdriver   # for webdriver

# Get URL first to load page to run script
driver('https://url.com')
driver.execute_script("window.localStorage.setItem('name', 'value');")

# Refresh the page
driver('https://url.com')

What is local storage?

A local storage token is a string of text that is stored on the client-side (typically within a web browser) and used to authenticate a user or retain user-specific information, such as preferences or session data. Local storage tokens are commonly used in web applications to persist user data even after the user has closed their browser or navigated away from the site, allowing for a more seamless experience between visits. The token is usually stored in the browser’s local storage or session storage, both of which are client-side storage mechanisms that allow websites to store data in a key-value format.

How to interact with local storage in Selenium?

A quick and dirty method is using pure javascript.

driver.execute_script is a method in the Selenium WebDriver Python API used to execute JavaScript code in the context of a web page. It allows you to interact with the web page’s Document Object Model (DOM) and perform actions such as clicking buttons, changing the values of form inputs, or manipulating the page’s content. The JavaScript code is executed as if it were written directly in the web page’s script tag, so it can interact with and modify the page in the same way as client-side JavaScript code.