从Splinter访问和管理本地存储?

时间:2016-02-19 15:16:13

标签: python local-storage browser-automation splinter

我想在本地存储中检索,管理和存储数据。

分裂中是否有API?

2 个答案:

答案 0 :(得分:3)

splinter没有可用的存储API,但您可以使用evaluate_script和execute_script构建自己的存储API:

import json
from splinter import Browser

class LocalStorage:

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

  def set(self, key, value):
    self.browser.execute_script(\
      "window.localStorage.setItem('{}',{})".format(key, json.dumps(value)))

  def get(self, key):
    return self.browser.evaluate_script(\
      "window.localStorage.getItem('{}')".format(key));

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

  def remove(self, key):
    self.browser.execute_script(\
      "window.localStorage.removeItem('{}');".format(key));

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

用法示例:

from splinter import Browser

browser = Browser()
browser.visit("http://mdn.github.io/web-storage-demo")

# get the local storage
storage = LocalStorage(browser)

# get an item
print storage.get("bgcolor")

# set an item
storage.set("size", 452)

# remove an item
storage.remove("size")

# get all items
for key, value in storage.get_all().iteritems():
  print key + ': ' + value

# delete all items
storage.clear()

答案 1 :(得分:1)

我假设如果你的分裂驱动程序能够执行java脚本,你可以这样做(我在selenium中使用过它):

from selenium import webdriver
driver = webdriver.Firefox() 
url='http://xxx.xxx.xxx/'
driver.get(url)
scriptArray="""return Array.apply(0, new Array(localStorage.length)).map(function (o, i) { return localStorage.getItem(localStorage.key(i)); }
                )"""    
result = driver.execute_script(scriptArray)
print(result)

我去年学习这项技术的原始帖子是here