从URL中获取前n个字节

时间:2011-10-30 11:47:50

标签: python urllib2 urllib

是否可以从某个URL获取少量字节,然后用urllib / urllib2关闭连接?或者甚至可能是第n个字节到第k个字节的一部分?那边有一个页面,我不需要加载整个页面,只需加载一页。

1 个答案:

答案 0 :(得分:6)

您可以设置Range标头以请求特定范围的字节,但是 您依赖服务器来履行请求:

import urllib2
req = urllib2.Request('http://www.python.org/')
#
# Here we request that bytes 18000--19000 be downloaded.
# The range is inclusive, and starts at 0.
#
req.headers['Range']='bytes=%s-%s' % (18000, 19000)
f = urllib2.urlopen(req)
# This shows you the actual bytes that have been downloaded.
content_range=f.headers.get('Content-Range')
print(content_range)
# bytes 18000-18030/18031