python 下载文件-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()

代理下载功能实现

在有些情况下,比如,为了安全,某些机器不能直接访问服务器时,代理是一个比较好的解决方案,而脚本中涉及到文件下载时,就需要在文件下载过程中增加一些操作了

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

特别注意:本站所有转载文章言论不代表本站观点!

本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值