【问题标题】:get file size before downloading using HTTP header not matching with one retrieved from urlopen在下载之前使用与从 urlopen 检索到的 HTTP 标头不匹配的文件大小获取文件大小
【发布时间】:2014-08-26 10:08:03
【问题描述】:

为什么在使用requestsurlopen(url).info() 的情况下内容长度不同

>>> url = 'http://pymotw.com/2/urllib/index.html'

>>> requests.head(url).headers.get('content-length', None)
'8176'
>>> urllib.urlopen(url).info()['content-length']
'38227'
>>> len(requests.get(url).content)
38274

我打算检查文件大小(以字节为单位),以根据urllib2 中的Range 将缓冲区拆分为多个线程,但如果我没有以字节为单位的文件实际大小,它将无法工作..

只有len(requests.get(url).content) 给出最接近但仍然不正确的38274,而且它正在下载我不想要的内容。

【问题讨论】:

  • 可能是服务器没有正确支持HEAD。或者,服务器可能会根据相应方法(用户代理、cookie ......)发送(或不发送)的其他标头返回不同的内容。尝试使用curl -v urlcurl -I,或任何其他发送完全相同请求的方法,除了HEAD,而不是post,并检查结果。
  • 也许第一个尺寸是压缩后的尺寸?
  • @BlackBear :那么如何获得未压缩的大小?
  • 您可以通过查看压缩方法进行(非常粗略的)估计。例如,gzip 的压缩比为 3:1 - 5:1(来源:superuser.com/questions/139253/…

标签: python python-requests urllib


【解决方案1】:

默认情况下,请求会发送'Accept-Encoding': 'gzip'作为请求头的一部分,服务器会以压缩后的内容进行响应:

>>> r = requests.head('http://pymotw.com/2/urllib/index.html')
r>>> r.headers['content-encoding'], r.headers['content-length']
('gzip', '8201')

但是,如果您手动设置请求标头,那么您将获得未压缩的内容:

>>> r = requests.head('http://pymotw.com/2/urllib/index.html',headers={'Accept-Encoding': 'identity'})
>>> r.headers['content-length']
'38227'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    相关资源
    最近更新 更多