How to keep cookies when making http requests (Python 2.7)

Fábio Santos fabiosantosart at gmail.com
Wed Aug 21 05:15:25 EDT 2013


On 21 Aug 2013 09:22, "Luca Cerone" <luca.cerone at gmail.com> wrote:
>
> >
> > I have used "cookielib" externally to "urllib2". It looks
> >
> > like this:
> >
> > from urllib2 import urlopen, Request
> >
> > from cookielib import CookieJar
> > cookies = CookieJar()
> >
> > ....
> >
> > r = Request(...)
> >
> > cookies.add_cookie_header(r) # set the cookies
> >
> > R = urlopen(r, ...) # make the request
> >
> > cookies.extract_cookies(R, r) # remember the new cookies
>
> Hi Dieter,
> thanks a lot for the help.
> I am sorry but your code is not very clear to me.
> It seems that you are setting some cookies,
> but I can't understand how you use the ones that the site
> sends to you when you perform the initial request.

This example does both. The cookie jar adds the cookies to the http request
to be sent to the server, and updates the cookies from the response, if any
were sent. It seems pretty clear, seeing that it has a lot of comments.

The cookies from the site are thus in the cookie jar object after the call
to extract_cookies() extracts them from the response.

> Have you tried this code to check if this work?
> If it works as intended can you explain a bit better
> what it does exactly?

You should really test this yourself ;)

> Thanks again!
> Luca
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130821/2bf1a439/attachment.html>


More information about the Python-list mailing list