Skip to main content
 首页 » 编程设计

python之使用 python 的 urllib2 urlopen 时缺少 'content-length' header

2025年05月04日14lovecherry

尝试在 python 中使用 urllib2 检查某些网页的“内容长度” header 时, header 丢失。例如,来自 google.com 的响应缺少此 header 。知道为什么吗?

例子:

r = urllib2.urlopen('http://www.google.com') 
i = r.info() 
print i.keys() 

给予:

['x-xss-protection', 'set-cookie', 'expires', 'server', 'connection', 'cache-control', 'date', 'p3p', 'content-type', 'x-frame-options'] 

请您参考如下方法:

可以看到here http 响应可以包含 Content-Length 或 Transfer-Encoding: chunked。

但是,当 Transfer-Encoding: chunked 用于 header 时,在 header 之后,您将得到一个十六进制字符串,如果将其转换为十进制,将为您提供下一个 block 的长度.在最后一个 block 之后,您将获得此值的 0,这意味着您已到达文件末尾。

您可以使用正则表达式来获取此十六进制值(虽然不是必须的)

read = #string containing a line or a part of the http response 
hexPat = re.compile(r'([0-9A-F]+)\r\n', re.I) 
match = re.search(hexPat, read) 
chunkLen = int(match.group(1), 16) #converts hexadecimal to decimal 

或者您可以只读取第一个十六进制值,获取第一个 block 的长度并接收该 block ,然后获取下一个 block 的长度,依此类推,直到找到 0