使用Python请求在请求之间设置新cookie

时间:2014-08-26 07:46:03

标签: python session cookies python-requests

我现在正在这样做,但它在TypeError: expected string or buffer的最后一行失败了。

import requests
from urllib.parse import urlparse

url = 'some url'

s = requests.Session()
s.headers.update({
    'Origin':urlparse(url).netloc,
    'Referer':url
})


r = s.get(url)

s.cookies['cookie1'] = 25
s.cookies['cookie2'] = 25

r = s.post(
    url,
    {'param':'value1', 'param2':'value2'},
    headers={'X-Requested-With':'XMLHttpRequest'}
)

使用Session时更新Cookie的正确方法是什么?我是Python的新手,所以我可能会感到困惑。使用Python 3.4.1。

回溯:

Traceback (most recent call last):
  File "file.py", line 37, in <module>
    {'param':'value1', 'param2':'value2'}
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/sessions.py", line 498, in post
    return self.request('POST', url, data=data, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/sessions.py", line 422, in request
    prep = self.prepare_request(req)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/sessions.py", line 360, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/models.py", line 296, in prepare
    self.prepare_cookies(cookies)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/models.py", line 491, in prepare_cookies
    cookie_header = get_cookie_header(self._cookies, self)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/cookies.py", line 134, in get_cookie_header
    jar.add_cookie_header(r)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1329, in add_cookie_header
    attrs = self._cookie_attrs(cookies)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1288, in _cookie_attrs
    self.non_word_re.search(cookie.value) and version > 0):
TypeError: expected string or buffer

1 个答案:

答案 0 :(得分:3)

Cookie值是字符串,而不是整数。将它们设置为:

s.cookies['cookie1'] = '25'
s.cookies['cookie2'] = '25'

演示:

>>> import requests
>>> from urllib.parse import urlparse
>>> url = 'http://httpbin.org/cookies'
>>> s = requests.Session()
>>> s.headers.update({
...     'Origin':urlparse(url).netloc,
...     'Referer':url
... })
>>> r = s.get(url)
>>> s.cookies['cookie1'] = '25'
>>> s.cookies['cookie2'] = '25'
>>> r = s.get(url, headers={'X-Requested-With':'XMLHttpRequest'})
>>> print(r.text)
{"cookies": {"cookie1": "25", "cookie2": "25"}}