如何使用Python获取、写入localStorage

python API没有提供直接读/写本地存储的方法,但可以使用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__()

用法示例:

# 获取 local storage
storage = LocalStorage(driver)

# 设置一个值 item
storage["mykey"] = 1234
storage.set("mykey2", 5678)

# 获取一个值 item
print(storage["mykey"])      # raises a KeyError if the key is missing
print(storage.get("mykey"))  # returns None if the key is missing

# 删除一个值 item
storage.remove("mykey")

# 循环取值 items
for i in storage:
    print(i, storage[i])

# 清空 items
storage.clear()

补充细节,循环赋值先把class对象转换为字典类型

# 循环赋值 items
storage = LocalStorage(driver)
print(storage)
d =dict(storage) #先把class对象转换为字典类型
print(d)
storage.clear()
driver.refresh()
storage.clear()
 #循环赋值
for i in d:
    print(i, d[i])
    storage.set(i, d[i])
driver.refresh()

出处:

https://www.thinbug.com/q/46361494

你可能感兴趣的:(如何使用Python获取、写入localStorage)