Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set and retrieve cookie in HTTP header in Python?

I need to get the cookies from a HTTP response sent by a server and put it in the next request's header. How can I do it?

Thanks in advance.

like image 469
Damodaran Avatar asked Apr 09 '11 16:04

Damodaran


People also ask

How do I set HTTP header cookies?

The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.

How do you pass cookies in Python request?

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.

How do I get the request header cookie?

To check this Cookie in action go to Inspect Element -> Network check the request header for Cookie like below, Cookie is highlighted you can see.

Is set-cookie a request header a response header or both?

The HTTP header Set-Cookie is a response header and used to send cookies from the server to the user agent.


1 Answers

Look at urllib module:

(with Python 3.1, in Python 2, use urllib2.urlopen instead) For retrieving cookies:

>>> import urllib.request
>>> d = urllib.request.urlopen("http://www.google.co.uk")
>>> d.getheader('Set-Cookie')
'PREF=ID=a45c444aa509cd98:FF=0:TM=14.....'

And for sending, simply send a Cookie header with request. Like that:

r=urllib.request.Request("http://www.example.com/",headers={'Cookie':"session_id=1231245546"})
urllib.request.urlopen(r)

Edit:

The "http.cookie"("Cookie" for Python 2) may work for you better:

http://docs.python.org/library/cookie.html

like image 105
utdemir Avatar answered Nov 09 '22 00:11

utdemir