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.
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.
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.
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.
The HTTP header Set-Cookie is a response header and used to send cookies from the server to the user agent.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With