tags:

views:

217

answers:

3

Hi,

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

A: 

Use cookielib. The linked doc page provides examples at the end. You'll also find a tutorial here.

Marcelo Cantos
In the tutorial they are saving cookie after receiving it from server isn't it?
Oleg Tarasenko
They are both saving cookies retrieved from the server and returning them back to the server, since this is usually how cookies work. If you want to do something out of the ordinary, then you'll have to dig a little deeper into the library. I'm pretty sure it'll support whatever you want to do.
Marcelo Cantos
A: 

This post should help you with what you want to do.

Martin
Reading the post. Looks like there is no such function: agent = urllib.urlopener()
Oleg Tarasenko
+3  A: 

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.

Messa