44

What's the equivalent of:

driver.get_cookies()

to get the LocalStorage instead of Сookies?

4 Answers 4

91

The python API doesn't provide a way to directly read/write the local storage, but it can be done with execute_script.

class LocalStorage:

    def __init__(self, driver) :
        self.driver = driver

    def __len__(self):
        return self.driver.execute_script("return window.localStorage.length;")

    def items(self) :
        return self.driver.execute_script( \
            "var ls = window.localStorage, items = {}; " \
            "for (var i = 0, k; i < ls.length; ++i) " \
            "  items[k = ls.key(i)] = ls.getItem(k); " \
            "return items; ")

    def keys(self) :
        return self.driver.execute_script( \
            "var ls = window.localStorage, keys = []; " \
            "for (var i = 0; i < ls.length; ++i) " \
            "  keys[i] = ls.key(i); " \
            "return keys; ")

    def get(self, key):
        return self.driver.execute_script("return window.localStorage.getItem(arguments[0]);", key)

    def set(self, key, value):
        self.driver.execute_script("window.localStorage.setItem(arguments[0], arguments[1]);", key, value)

    def has(self, key):
        return key in self.keys()

    def remove(self, key):
        self.driver.execute_script("window.localStorage.removeItem(arguments[0]);", key)

    def clear(self):
        self.driver.execute_script("window.localStorage.clear();")

    def __getitem__(self, key) :
        value = self.get(key)
        if value is None :
          raise KeyError(key)
        return value

    def __setitem__(self, key, value):
        self.set(key, value)

    def __contains__(self, key):
        return key in self.keys()

    def __iter__(self):
        return self.items().__iter__()

    def __repr__(self):
        return self.items().__str__()

Usage example:

# get the local storage
storage = LocalStorage(driver)

# set an item
storage["mykey"] = 1234
storage.set("mykey2", 5678)

# get an item
print(storage["mykey"])      # raises a KeyError if the key is missing
print(storage.get("mykey"))  # returns None if the key is missing

# delete an item
storage.remove("mykey")

# iterate items
for key, value in storage.items():
  print("%s: %s" % (key, value))

# delete items
storage.clear()
Sign up to request clarification or add additional context in comments.

5 Comments

Can saved values be accessed after closing and reopening the browser?
Probably not, as each new window is in Incognito mode.
cool implementation
I tried this solution on local storage having more than one items/entries by executing this command print(storage.items()) but it gives me empty dict. Any solution??
Any idea how to make storage.clear() work in geckodriver without getting JavascriptException: SecurityError: The operation is insecure?
30

I solved using:

driver.execute_script("return window.localStorage;")

EDIT: this is a quick and short answer. See Florent B.'s answer for a more detailed one.

Comments

8

See the answer to the question Getting the return value of Javascript code in Selenium.

Basically, you need to do something like the following:

from selenium import webdriver

wd = webdriver.Firefox()
wd.get("http://localhost/foo/bar")
wd.execute_script("return localStorage.getItem('foo')")

Comments

6

Try:

driver.execute_script("window.localStorage.setItem('key','value');")
driver.execute_script("window.localStorage.getItem('key');")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.