How to make a request by sending cookie data?

4

I want to make a GET request for a given URL, but I want to send cookie data as a web browser does.

For example, in the code below:

from urllib import request
req = request.Request('http://servidor/pagina.html')
response = request.urlopen(req)
print(response.read().decode())

If I print the headers, the result is an empty list:

print(req.header_items())

But I want to send a header HTTP like this:

Cookie: atributo=valor+do+atributo

Part of the question for anyone who is already experienced with Python:

  

I am in the Level 17 of pythonchallenge.com and I need to make a request by sending an "info" cookie. with the value "the + flowers + are + on + their + way" to link .

    
asked by anonymous 05.02.2014 / 16:01

2 answers

2

I was able to partially resolve the issue with the add_header method of the object request .

from urllib import request
req = request.Request('http://servidor/pagina.html')

req.add_header('Cookie', 'atributo=valor+do+atributo')

response = request.urlopen(req)
print(response.read().decode())

The problem is that this way I have to do the encode of the cookie attributes manually.

I could not resolve the issue with a Cookie object:

from http import cookiejar
cookie = cookiejar.Cookie(1, 'atributo', 'valor do atributo',
                          80, True, 'www.servidor.com', True, True,
                          '/', True, False, -1, False, None, None, None)
    
05.02.2014 / 16:01
2

I never programmed Python, but looking at docs.python-requests.org I think you can do it like this:

url = 'http://servidor/pagina.html'
cookies = dict(info='the+flowers+are+on+their+way')

req = requests.get(url, cookies=cookies)
req.text  # '{"cookies": {"info": "the+flowers+are+on+their+way"}}' 
    
05.02.2014 / 16:37