Python-获取Local Storage和Session Storage
一、简介
LocalStorage 是只读的。数据存储也是跨浏览器会话。LocalStorage 类似于SessionStorage。
区别在于,数据存储在 LocalStorage 是无期限的,而当页面会话结束——也就是说当页面被关闭时,数据存储在 SessionStorage 会被清除 。
二、演示示例
三、代码实现
# -*- coding:UTF-8 -*- from selenium.webdriver.common.by import By from selenium import webdriver from time import sleep import yaml USER_MES = ['你的账号', '你的密码'] # 账号密码 LOCAL_STORAGE_PATH = '你的生成yaml文件路径' class Get_storage(object): user_name_loc = (By.XPATH, "lalala") pass_word_loc = (By.XPATH, "dididi") login_button_loc = (By.XPATH, "lilili") def get_localstorage(self): # 获取localStorage配置 driver = webdriver.Chrome() driver.get("你的测试链接") driver.find_element(*self.user_name_loc).send_keys(USER_MES[0]) # 输入账号 driver.find_element(*self.pass_word_loc).send_keys(USER_MES[1]) # 输入密码 driver.find_element(*self.login_button_loc).click() # 登录 sleep(3) # 获取 Session Storage 只需将 localStorage 修改为 sessionStorage,修改获取的值为 token_bk 即可 local_storage = driver.execute_script("return window.localStorage") with open(LOCAL_STORAGE_PATH, "w") as f: # 第一个参数是要写入的数据,第二个字段是要进行数据操作的资源文件 yaml.safe_dump(local_storage, f) print("保存成功") def set_localstorage(self, driver): # 写入localStorage,在driver.get("xxxx")后调用此函数即可写入获取的值 localstorage = yaml.safe_load(open(LOCAL_STORAGE_PATH)) for key, value in localstorage.items(): driver.execute_script("localStorage.setItem(arguments[0],arguments[1]);", key, value) driver.refresh()
执行完成即可查看生成的.yaml文件