Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python requests get cookies

x = requests.post(url, data=data) print x.cookies 

I used the requests library to get some cookies from a website, but I can only get the cookies from the Response, how to get the cookies from the Request? Thanks!

like image 379
Danfi Avatar asked Aug 02 '14 05:08

Danfi


People also ask

Does Python request save cookies?

Expanding on @miracle2k's answer, requests Session s are documented to work with any cookielib CookieJar . The LWPCookieJar (and MozillaCookieJar ) can save and load their cookies to and from a file. Here is a complete code snippet which will save and load cookies for a requests session.

How do you pass cookies in request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

How do you read cookies in Python?

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. The get() method of the request.


1 Answers

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests >>> session = requests.Session() >>> print(session.cookies.get_dict()) {} >>> response = session.get('http://google.com') >>> print(session.cookies.get_dict()) {'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'} 
like image 76
alecxe Avatar answered Oct 08 '22 15:10

alecxe