从 URL 中获取前 n 个字节 [英] Fetch first n bytes from the URL

查看:28
本文介绍了从 URL 中获取前 n 个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is that possible to fetch only a number of bytes from some URL and then close the connection with urllib/urllib2? Or even may be a part from n-th byte to k-th? There is a page on that side and I don't need to load the whole page, only a piece of it.

推荐答案

可以设置Range头来请求一定范围的字节,但是您依赖服务器来满足请求:

You can set the Range header to request a certain range of bytes, but you are dependent on the server to honor the request:

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

这篇关于从 URL 中获取前 n 个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆