当前位置:   article > 正文

python将学生信息保存到文件中_如何将请求(python)cookie保存到文件中?

requests.cookies.requestscookiejar 导出到文件

通话结束后,如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))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/608261
推荐阅读
相关标签
  

闽ICP备14008679号