我正在搜索类似于Python pickle的内容。我想这样做:
https://www.quora.com/Is-there-a-way-to-keep-the-session-after-login-with-Selenium-Python
保存Cookie
import pickle
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.quora.com')
# login code
pickle.dump(driver.get_cookies() , open("QuoraCookies.pkl","wb"))
加载Cookie
import pickle
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.quora.com')
for cookie in pickle.load(open("QuoraCookies.pkl", "rb")):
driver.add_cookie(cookie)
我在网上尝试过很多没有成功的例子。我也在这里看到了这些话题。
在groovy case I' ll:
Set<Cookie> allCookies = driver.manage().getCookies();
变量allCookies应序列化为文件并稍后反序列化。
答案 0 :(得分:1)
Java序列化是一个选项。归功于this post,这是一个实现:
import org.openqa.selenium.Cookie
def loadFile = { filename ->
def result = null
try {
def fis = new FileInputStream(filename)
def instream= new ObjectInputStream(fis)
result = (Set<Cookie>) instream.readObject()
instream.close()
} catch (Exception e) {
System.out.println(e)
}
return result
}
def saveFile = { set, filename ->
try {
def fos = new FileOutputStream(filename)
def out = new ObjectOutputStream(fos)
out.writeObject(set)
out.flush()
out.close()
} catch (IOException e) {
System.out.println(e)
}
}
和示例驱动程序:
// ----------------------- main
if (args.size() >= 2) {
def action = args[0]
def file = args[1]
if (action == "write") {
def cookies = new HashSet<Cookie>()
cookies << new Cookie("Toronto", "Canada")
cookies << new Cookie("London", "UK")
cookies << new Cookie("Paris", "France")
saveFile(cookies, file)
} else if (action == "read") {
def cookies = loadFile(file)
cookies.each { cookie ->
println "${cookie.name} ${cookie.value}"
}
} else {
println "Unknown action: " + action
}
} else {
println "Usage: groovy CookieManager.groovy [read|write] filename"
}
示例用法(a)在同一个脚本中包含所有上述代码,(b)假设client-combined-3.0.0-beta2-nodeps.jar
from here在类路径中:
bash$ groovy CookieManager.groovy write set.dat
bash$ groovy CookieManager.groovy read set.dat
London UK
Toronto Canada
Paris France