Python實現http文件下載
在自動化腳本中,文件下載是比較常見的操作,一般情況下,我們會將文件放到某個http服務器上,這時,當腳本中需要這個文件時,就需要使用到http下載的功能了
最基本的下載功能實現
實現最基本的功能,傳入文件下載路徑和文件本地保存路徑,下載到本地
def DownloadFile(url,savePath): """ | ##@函數目的: 下載文件 | ##@參數說明:url:文件的url路徑 | ##@參數說明:savePath:文件保存到的位置 | ##@返回值: """ 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()</pre>
代理下載功能實現
在有些情況下,比如,為了安全,某些機器不能直接訪問服務器時,代理是一個比較好的解決方案,而腳本中涉及到文件下載時,就需要在文件下載過程中增加一些操作了
def DownloadFilebyProxy(url , savePath , host , port , user , pwd ): try: url = url.strip() savePath = savePath.strip() InitPath(savePath)#如果代理需要驗證 proxy_info = {'host' : host, 'port' : int(port), 'user' : user, 'pass' : pwd } proxy_support = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(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()</pre>
上面對http下載功能做了簡單的介紹,當然,有些情況下,我們需要通過腳本對ftp、ssh等服務器進行操作~·~
本文由用戶 ybw8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!