我正在使用urllib2与一个发送多个Set-Cookie头信息的网站进行交互。然而,响应头字典只包含一个 - 似乎重复的键会相互覆盖。
有没有办法使用urllib2访问重复的头信息?
.headers
属性是一个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'
这对我来说绝对不是问题。我在浏览器开发工具中运行了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。set-cookie
则有所不同。来自 RFC 6265 的说明为:
起始服务器不应将多个Set-Cookie头字段合并为单个头字段。HTTP标头字段折叠的通常机制(即[RFC2616]中定义的机制)可能会更改Set-Cookie头字段的语义,因为在Set-Cookie中使用了%x2C(“,”)字符,这与此类折叠存在冲突。
理论上看,这似乎是一个错误。
Lib/cookielib
。 - Jason R. Coombs