In automation scripts, file download is a more common operation, in general, we will put the file on an HTTP server, when the script needs this file, you need to use the HTTP download function
The most basic download function implementation
To achieve the most basic functions, the incoming file download path and file local save path, download to local
def DownloadFile (Url,savepath): "" " | ##@ function Purpose: Download file | ##@ parameter description: url: File URL path | ##@ Parameter description: Savepath: Where to save the file | ##@ return value: "" " try: url = url.strip () Savepath = Savepath.strip () Initpath (savepath) r = urllib2. Request (URL) req = Urllib2.urlopen (r) saveFile = open (Savepath, ' WB ') Savefile.write (Req.read ()) savefile.close () req.close () except: print Traceback.format_exc ()
Agent download Feature implementation
In some cases, for example, for security, some machines do not have direct access to the server, the proxy is a better solution, and the script involves file download, you need to add some action during the file download process
def downloadfilebyproxy (URL, Savepath, host, port, user, PWD): try: url = url.strip () Savepath = Savepat H.strip () Initpath (savepath) #如果代理需要验证 proxy_info = {' Host ': Host, ' Port ': Int (port), ' user ': User, ' pass ': pwd } proxy_support = Urllib2. Proxyhandler ({"http": "http://% (user) s:% (pass) [email protected]% (host) s:% (port) d"% Proxy_info}) opener = Urllib2.build_opener (Proxy_support) Urllib2.install_opener (opener) req = Urllib2.urlopen (URL) SaveFile = open (Savepath, ' WB ') Savefile.write (Req.read ()) savefile.close () req.close () Except: print Traceback.format_exc ()
The above is a brief introduction to the HTTP download function, of course, in some cases, we need to script the FTP, SSH and other servers to operate ~ ~
Python write automation http file download