如何保存请求(python)cookie到文件? [英] How to save requests (python) cookies to a file?
问题描述
如何在请求后使用库请求(在python中)
How to use the library requests
(in python) after a request
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
bot = requests.session()
bot.get('http://google.com')
以保存文件中的所有Cookie然后从文件中恢复Cookie。
to keep all the cookies in a file and then restore the cookies from a file.
推荐答案
没有直接的方法,但这并不难。
There is no immediate way to do so, but it's not hard to do.
您可以从会话中获取 CookieJar
对象 session.cookies
。您可以使用 requests.utils.dict_from_cookiejar
将其转换为dict。然后,您可以使用 pickle
将其存储到文件(您还可以使用 shelve
(如果需要)
You can get a CookieJar
object from the session as session.cookies
. You can use requests.utils.dict_from_cookiejar
to transform it into a dict. Then, you can use pickle
to store it to a file (you can also use shelve
if you need to store more than one thing).
一个完整的例子:
import requests, requests.utils, pickle
session = requests.session()
# Make some calls
with open('somefile', 'w') as f:
pickle.dump(requests.utils.dict_from_cookiejar(session.cookies), f)
/ p>
Loading is then :
with open('somefile') as f:
cookies = requests.utils.cookiejar_from_dict(pickle.load(f))
session = requests.session(cookies=cookies)
这篇关于如何保存请求(python)cookie到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!