本文介绍了如何将请求 (python) cookie 保存到文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请求后如何使用库requests(在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.

您可以使用 session.cookies 从会话中获取 CookieJar 对象,并使用 pickle 将其存储到文件中.

You can get a CookieJar object from the session with session.cookies, and use pickle to store it to a file.

一个完整的例子:

import requests, pickle
session = requests.session()
# Make some calls
with open('somefile', 'wb') as f:
    pickle.dump(session.cookies, f)

然后加载:

session = requests.session()  # or an existing session

with open('somefile', 'rb') as f:
    session.cookies.update(pickle.load(f))

requests 库使用 requests.cookies.RequestsCookieJar() 子类,它明确支持酸洗和类似 dict 的 API.RequestsCookieJar.update() 方法 可用于使用从pickle 文件加载的cookie 更新现有会话cookie jar.

The requests library uses the requests.cookies.RequestsCookieJar() subclass, which explicitly supports pickling and a dict-like API. The RequestsCookieJar.update() method can be used to update an existing session cookie jar with the cookies loaded from the pickle file.

这篇关于如何将请求 (python) cookie 保存到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:18