如何从python中的http响应urllib获取有关大小的信息

时间:2013-09-01 06:09:58

标签: python python-2.7 urllib2 httpresponse urllib

基本上我在一些视频文件列表中的网址很少,我想找到这些视频的大小,而不是使用urllib下载它们。

[u'https://fbcdn-video-a.akamaihd.net/hvideo-ak-frc3/v/985732_10102527799850656_17701053_n.mp4?oh=a4d452753fd4cc90aeca55b3e1b23d4f&oe=5222F54B&__gda__=1378022845_fc6b392b6b1238ab60bde944da7a1cfe', u'https://fbcdn-video-a.akamaihd.net/hvideo-ak-ash4/v/1039184_10102527799376606_136270614_n.mp4?oh=d3198aa784f5da432d56236135fffa4b&oe=5222F6C7&__gda__=1378023085_1c5de4e6d733269f70643fc3a25c09e5']

可以使用urllib的info()方法完成吗? 有什么方法可以让我们得到它们的大小。

提前致谢

2 个答案:

答案 0 :(得分:3)

虽然@sberry的答案完全有效,但我只是将其翻译成Python,因为它是你问题的标记。

import requests

>>> r = requests.head(url)
>>> print r.headers
{'accept-ranges': 'bytes',
 'cache-control': 'max-age=467354',
 'connection': 'keep-alive',
 'content-length': '37475248',
 'content-type': 'video/mp4',
 'date': 'Sun, 01 Sep 2013 07:26:21 GMT',
 'expires': 'Fri, 06 Sep 2013 17:15:35 GMT',
'last-modified': 'Fri, 09 Aug 2013 18:51:33 GMT'}
video_size = r.headers.get('content-length')

如果您不想安装新软件包,可以使用httplib2urllib2(尽管后者有点hacky)。

import httplib2

r = httplib2.Http()
response, _ = r.request(url, 'HEAD')
video_size = response.get('content-length')


# or with urllib2
import urllib2

r = urllib2.Request(url)

# here, we modify the Request.get_method() instance method
# so that is returns 'HEAD' instead of 'GET'
r.get_method = lambda: 'HEAD'
response = urllib2.urlopen(r)

# then you need to parse the response, as it is just raw_text

答案 1 :(得分:1)

您可以发出HEAD请求而不是GET。

例如,

curl -i -X HEAD https://some.url.com

HTTP/1.1 200 OK
Content-Type: image/jpeg
Last-Modified: Sun, 01 Sep 2013 05:04:13 GMT
Content-Length: 83909
Date: Sun, 01 Sep 2013 06:17:34 GMT
Connection: keep-alive
Cache-Control: max-age=1209600