如何保存请求(python)cookie到文件?

编程入门 行业动态 更新时间:2024-10-24 12:30:04
本文介绍了如何保存请求(python)cookie到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在请求后使用库请求(在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到文件?

本文发布于:2023-10-11 23:26:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483138.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   python   cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!