How to make a request by sending cookie data?

Asked

Viewed 1,015 times

4

I want to file a requisition GET for a particular 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 already experienced with Python:

I’m in the Level 17 pythonchallenge.com and need to make a request by sending an "info" cookie with the value "the+Flowers+are+on+their+way" to the url http://www.pythonchallenge.com/pc/stuff/violin.php.

2 answers

2

I never programmed Python, but looking at us 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"}}' 
  • Maicon, this really might be a solution. But this library does not come with Python and at this point I wanted to avoid the use and installation of external libraries. Hug.

  • Got it, thanks for the warning.

2


I was able to partially resolve the issue with the method add_header 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 way I have to do the encounter of the cookie attributes manually.

I couldn’t resolve the issue with an object Cookie:

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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.