python: urllib2 how to send cookie with urlopen request

Oleg Tarasenko picture Oleg Tarasenko · Jul 26, 2010 · Viewed 129.7k times · Source

I am trying to use urllib2 to open url and to send specific cookie text to the server. E.g. I want to open site Solve chess problems, with a specific cookie, e.g. search=1. How do I do it?

I am trying to do the following:

import urllib2
(need to add cookie to the request somehow)
urllib2.urlopen("http://chess-problems.prg")

Thanks in advance

Answer

Messa picture Messa · Jul 26, 2010

Cookie is just another HTTP header.

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

See urllib2 examples for other ways how to add HTTP headers to your request.

There are more ways how to handle cookies. Some modules like cookielib try to behave like web browser - remember what cookies did you get previously and automatically send them again in following requests.