Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 771
Natim Avatar asked Jan 07 '10 15:01

Natim


People also ask

How do I download from Python using wget?

You'll use the wget command, give it a URL, and provide specific options to achieve certain goals. Check your options in the extensive manual. Download a file: To download a file from a server, pass the wget command and the file URL to the custom function you created. Set verbose to True .

How do I download a file using Python curl?

To download a file with Curl, use the --output or -o command-line option. This option allows you to save the downloaded file to a local drive under the specified name. If you want the uploaded file to be saved under the same name as in the URL, use the --remote-name or -O command line option.


1 Answers

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.

like image 187
unutbu Avatar answered Sep 19 '22 12:09

unutbu