我正在使用 urllib2 与发送回多个 Set-Cookie 标头的网站进行交互。然而,响应头字典只包含一个 - 似乎重复的键相互覆盖。
有没有办法使用 urllib2 访问重复的标头?
根据urllib2 docs,.headers
结果 URL 对象的属性是 an httplib.HTTPMessage
(至少在 Python 文档中似乎没有记录)。
然而,
help(httplib.HTTPMessage)
...
If multiple header fields with the same name occur, they are combined
according to the rules in RFC 2616 sec 4.2:
Appending each subsequent field-value to the first, each separated
by a comma. The order in which header fields with the same field-name
are received is significant to the interpretation of the combined
field value.
因此,如果您访问 u.headers['Set-Cookie'],您应该获得一个 Set-Cookie 标头,其值以逗号分隔。
确实,情况似乎如此。
import httplib
from StringIO import StringIO
msg = \
"""Set-Cookie: Foo
Set-Cookie: Bar
Set-Cookie: Baz
This is the message"""
msg = StringIO(msg)
msg = httplib.HTTPMessage(msg)
assert msg['Set-Cookie'] == 'Foo, Bar, Baz'
set-cookie
虽然是不同的。来自 RFC 6265:
源服务器不应将多个 Set-Cookie 标头字段折叠成单个标头字段。折叠 HTTP 标头字段的常用机制(即,如 [RFC2616] 中定义的)可能会更改 Set-Cookie 标头字段的语义,因为 Set-Cookie 以一种冲突的方式使用 %x2C (",") 字符有了这样的折叠。
理论上,这看起来像一个错误。
这对我来说绝对不是这样。我Python 3.10.0
在浏览器开发工具中运行 OCS 提供了这两个 Set-Cookie 标头:
**set-cookie**:
JSESSIONID=node01v0bwkcyhmqot1a3eqp3lcvwd2600.node0;
Path=/;
Secure;
HttpOnly;
SameSite=Lax
**set-cookie**:
ZS-TOKEN-ID=apt688t8gfqf7r4zgkv60aii;
HttpOnly;
SameSite=Lax;
Path=/;
Secure;
Max-Age=36000
在r.headers['Set-Cookie']
它们没有组合。仅列出第一个 cookie。