在自动化脚本中,文件下载是比较常见的操作,一般情况下,我们会将文件放到某个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://blog.csdn.net/sogouauto/article/details/43668713