2016-02-19 58 views

回答

3

有可用的分裂沒有存儲API,但你可以evaluate_script和execute_script建立你自己:

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

我認爲,如果你對分裂的驅動程序能夠執行Java腳本,你可以做這樣的事情(我在硒用它):

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

相關問題