赞
踩
通话结束后,如r = requests.get(),r.cookies会返回一个RequestsCookieJar您可以直接pickle,即
import pickle
def save_cookies(requests_cookiejar, filename):
with open(filename, 'wb') as f:
pickle.dump(requests_cookiejar, f)
def load_cookies(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
#save cookies
r = requests.get(url)
save_cookies(r.cookies, filename)
#load cookies and do a request
requests.get(url, cookies=load_cookies(filename))
如果你想以可读的格式保存您的Cookie,您必须执行一些操作才能将RequestsCookieJar提取为LWPCookieJar。
import cookielib
def save_cookies_lwp(cookiejar, filename):
lwp_cookiejar = cookielib.LWPCookieJar()
for c in cookiejar:
args = dict(vars(c).items())
args['rest'] = args['_rest']
del args['_rest']
c = cookielib.Cookie(**args)
lwp_cookiejar.set_cookie(c)
lwp_cookiejar.save(filename, ignore_discard=True)
def load_cookies_from_lwp(filename):
lwp_cookiejar = cookielib.LWPCookieJar()
lwp_cookiejar.load(filename, ignore_discard=True)
return lwp_cookiejar
#save human-readable
r = requests.get(url)
save_cookies_lwp(r.cookies, filename)
#you can pass a LWPCookieJar directly to requests
requests.get(url, cookies=load_cookies_from_lwp(filename))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。