Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save requests (python) cookies to a file?

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') 

to keep all the cookies in a file and then restore the cookies from a file.

like image 497
agrynchuk Avatar asked Oct 23 '12 12:10

agrynchuk


People also ask

How do you store cookies in Python?

Create cookie In Flask, set the cookie on the response object. Use the make_response() function to get the response object from the return value of the view function. After that, the cookie is stored using the set_cookie() function of the response object. It is easy to read back cookies.

How do I send a cookie in Python?

To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.


1 Answers

There is no immediate way to do so, but it's not hard to do.

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

A full example:

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

Loading is then:

session = requests.session()  # or an existing session  with open('somefile', 'rb') as f:     session.cookies.update(pickle.load(f)) 

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.

like image 114
madjar Avatar answered Sep 19 '22 06:09

madjar