在自动化脚本中,文件下载是比较常见的操作,一般情况下,我们会将文件放到某个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()
代理下载功能实现
在有些情况下,比如,为了安全,某些机器不能直接访问服务器时,代理是一个比较好的解决方案,而脚本中涉及到文件下载时,就需要在文件下载过程中增加一些操作了
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()
上面对http下载功能做了简单的介绍,当然,有些情况下,我们需要通过脚本对ftp、ssh等服务器进行操作~·~
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。