我正在使用 Requests 编写一个 Python 2.7 脚本来自动访问一个网站,该网站设置了两个名称相同但域不同的 cookie,例如名称为“mycookie”,域为“www.example.com”和“subdomain.example.com”。我的客户端脚本需要读取这些 cookie 中的一个 的值,并将其作为参数包含在后续请求中。因为 requests.Session
中的 cookie 访问似乎仅由 cookie 名称键入,所以我看不到提取正确 cookie 值的方法。实际上,尝试使用该名称访问 cookie 会产生此错误:
value = session.cookies["mycookie"]
File "/usr/lib/python2.7/site-packages/requests/cookies.py", line 276, in __getitem__
return self._find_no_duplicates(name)
File "/usr/lib/python2.7/site-packages/requests/cookies.py", line 326, in _find_no_duplicates
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
requests.cookies.CookieConflictError: There are multiple cookies with name, 'mycookie'
这表明 Requests 是在假设每个 session 的 cookie 名称都是唯一的情况下编写的。然而,正如证明的那样,这不一定是真的。
我想我可以通过维护两个 session 并在它们之间手动复制其他重要的 cookie 来解决这个问题。但是,我想知道这是否是 Requests 的已知限制,如果是,建议的解决方法是什么?
最佳答案
Session.cookies
不是字典,它是 RequestsCookieJar
。尝试使用方法 RequestsCookieJar.get()
,其定义如下:
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains. Caution: operation is O(n), not O(1)."""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
对于您的代码,这意味着更改为:
value = session.cookies.get("mycookie", domain=relevant_domain)
至于请求,我们知道 cookie 名称不是唯一的。 =)
关于python - 请求 - 无法处理两个具有相同名称、不同域的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27586779/