Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests including cookies error out

I'm trying to make a get requests on python using the Requests module while incorporating an existing Cookie, and here's what my code looks like:

import requests

url="https://stackoverflow.com/"
headers = {"User-Agent", "Mozilla/5.0"}
cookie = {
    "domain": ".stackoverflow.com",
    "expirationDate": "1458316186",
    "hostOnly": "false",
    "httpOnly": "false",
    "name": "__qca",
    "path": "/",
    "secure": "false",
    "session": "false",
    "storeId": "0",
    "value": "P0-SOMEVALUE-SOMEVALUE",
    "id": 1
}

print requests.get(url, cookies=cookie).text


Traceback (most recent call last):
  File "test.py", line 19, in <module>
    print requests.get(url, cookies=cookie).text
  File "C:\Python27\lib\site-packages\requests\api.py", line 55, in get
    return request('get', url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 422, in request
    prep = self.prepare_request(req)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 360, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Python27\lib\site-packages\requests\models.py", line 296, in prepare
    self.prepare_cookies(cookies)
  File "C:\Python27\lib\site-packages\requests\models.py", line 491, in prepare_cookies
    cookie_header = get_cookie_header(self._cookies, self)
  File "C:\Python27\lib\site-packages\requests\cookies.py", line 134, in get_cookie_header
    jar.add_cookie_header(r)
  File "C:\Python27\lib\cookielib.py", line 1326, in add_cookie_header
    attrs = self._cookie_attrs(cookies)
  File "C:\Python27\lib\cookielib.py", line 1285, in _cookie_attrs
    self.non_word_re.search(cookie.value) and version > 0):
TypeError: expected string or buffer

Not entirely sure what I'm doing wrong...

like image 797
Stupid.Fat.Cat Avatar asked Sep 29 '22 19:09

Stupid.Fat.Cat


1 Answers

Cookies are supposed to be just key-value pairs. You included far more, you included all the metadata a browser tracks for cookies, governing how such cookies can be returned or accessed by client side code.

Make your cookie just the one key-value pair:

cookies = {'__qca': 'P0-SOMEVALUE-SOMEVALUE'}

Everything else in your mapping is not part of the Cookie header sent to the server.

In this specific case it is the 'id': 1 key-value pair that throws the exception, because requests expected the value of what it sees as the id cookie to be a string, not an integer.

like image 88
Martijn Pieters Avatar answered Oct 03 '22 01:10

Martijn Pieters