从URL中获取前n个字节

Ser*_*rov 4 python urllib urllib2

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

unu*_*tbu 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
Run Code Online (Sandbox Code Playgroud)