我正在用 Python 编写软件以从数据库下载 HTTP PDF。 有时下载会停止并显示此消息:
retrieval incomplete: got only 3617232 out of 10689634 bytes
如何使用 206 Partial Content
HTTP 功能要求下载从停止的地方重新开始?
我可以使用 wget -c
来完成它并且它工作得很好,但我想直接在我的 Python 软件中实现它。
有什么想法吗?
谢谢
最佳答案
您可以通过发送带有 Range
header 的 GET 来请求部分下载:
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.
range=f.headers.get('Content-Range')
print(range)
# bytes 18000-18030/18031
print(repr(f.read()))
# ' </div>\n</body>\n</html>\n\n\n\n\n\n\n'
小心检查 Content-Range
以了解实际下载了哪些字节,因为您的范围可能超出范围,和/或并非所有服务器似乎都遵守 Range
header 。
关于python - 使用 wget -c 功能在 Python 中使用 urllib 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2021519/