如何在请求后使用库请求(在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('google')以保存文件中的所有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到文件?
发布评论