Friday, February 19, 2010

python urllib2 handle cookies

To handle python cookies in urllib2, it's already provide with new urllib2.

Here is a example to deal with cookies return from http server.
opener = urllib2.build_opener(HTTPCookieProcessor(),HTTPBasicAuthHandler(),HTTPDefaultErrorHandler( ))
opener.addheaders = [('User-agent', 'Mozilla/5.0'),("Content-type", "text/xml; charset=\"UTF-8\"")]
opener.open(url)
urllib2.install_opener(opener)
urllib2.open(new_url)

We have register the opener into urllib2, afterward; we can use urllib2.open() without worry about handling cookies return.

No comments:

Post a Comment