urllib2多个Set-Cookie标头作为响应

hoj*_*oju 3 python header urllib2 setcookie

我正在使用urllib2与发回多个Set-Cookie标头的网站进行交互.但是响应头字典只包含一个 - 似乎重复的键相互重叠.

有没有办法用urllib2访问重复的标头?

Jas*_*mbs 5

根据urllib2文档,.headers结果URL对象的属性是一个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.
Run Code Online (Sandbox Code Playgroud)

因此,如果您访问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'
Run Code Online (Sandbox Code Playgroud)