Download file using urllib in Python with the wget -c feature

早过忘川 提交于 2019-12-18 04:14:50

问题


I am programming a software in Python to download HTTP PDF from a database. Sometimes the download stop with this message :

retrieval incomplete: got only 3617232 out of 10689634 bytes

How can I ask the download to restart where it stops using the 206 Partial Content HTTP feature ?

I can do it using wget -c and it works pretty well, but I would like to implement it directly in my Python software.

Any idea ?

Thank you


回答1:


You can request a partial download by sending a GET with the Range header:

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'

Be careful to check the Content-Range to learn what bytes have actually been downloaded, since your range may be out of bounds, and/or not all servers seem to respect the Range header.



来源:https://stackoverflow.com/questions/2021519/download-file-using-urllib-in-python-with-the-wget-c-feature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!