The front-end time encounters a need to download files through a URL, simply write a py script. From the web search for the implementation of the Python file download method, summarized as follows, for reference.
The following methods have been tested, environment win8.1 python2.6/2.7
to be added. --20150507
method one:
use urllib module provides The Urlretrieve () function. The Urlretrieve () method downloads remote data directly to the local.
Urlretrieve (URL, [Filename=none, [Reporthook=none, [Data=none]])
Description
The parameter finename specifies that the local path is saved (Urllib generates a temporary file to hold the data if the parameter is not specified.) )
-
parameter Reporthook is a callback function that triggers the callback when the server is connected and the corresponding data block is transferred. We can use this callback function to display the current download progress.
-
parameter data refers to a post to the server, the method returns a two-element (filename, headers) tuple, filename represents the path saved to a local, and the header represents the server's response header.
instance:
#!/usr/bin/python#encoding:utf-8import Urllibimport osdef schedule (a,b,c): " a: Data blocks already downloaded b: Size of data block c: Remote file size ' ' Per = 100.0 * a * b / c if per > 100 : per = 100 print '%.2f%% ' % perurl = ' http://www.python.org/ftp/python/2.7.5/ python-2.7.5.tar.bz2 ' #local = url.split ('/') [ -1]local = os.path.join ('/data/software ', ' python-2.7.5.tar.bz2 ') Urllib.urlretrieve (url,local,schedule) ##### #output ###### #0.00% #0.07% #0.13% #0.20%#....# 99.94% #100.00%
source: http://www.nowamagic.net/ academy/detail/1302861
method two:
Urllib () function using Urlopen
instance:
method three:
Use requests module
requests module Download: https:// pypi.python.org/pypi/requests/#downloads
instance:
A summary of how Python implements file downloads