python程序下载大量天文学数据

文件下载模块

首先编写一个专门用于下载文件的函数

def downloadFile(name,url,TIMEOUT):
    #download File, name=File, url=download address,TIMEOUT是超时时间,并返回下载状态
    headers = {
   'Proxy-Connection':'keep-alive'}
    i = 0
    while i < 3: #尝试三次
        try:
            r = requests.get(url,timeout=TIMEOUT,stream=True, headers=headers)#TIMEOUT 设置超时
            length = float(r.headers['content-length']) #文件长度
            f = open(name, 'wb')
            count = 0
            count_tmp = 0
            time1 = time.time()
            for chunk in r.iter_content(chunk_size = 512):
                if chunk:
                    f.write(chunk)
                    count += len(chunk)
                    if time.time() - time1 > 2:  #2s 统计一次
                        p = count / length * 100 #下载百分比
                        speed = (count - count_tmp) / 1024 / 1024 / 2#速度 MB/S
                        count_tmp = count
                        print(name + ': ' + formatFloat(p) + '%' + ' Speed: ' + formatFloat(speed) + 'MB/S')
                        time1 = time.time()
            print(name + ': download finished!')
            f.close()
            return 'successful'
        except requests.exceptions.RequestException:#超时异常
            print(name+'connect timeout——try again',i+1)
            i = i + 1#只有超时异常才尝试三次
        except KeyError:#IO异常
            print(name+'无效链接\n')
            i=3
            return 'link_error'
        except Exception:#所有其它异常
            print(name+"下载错误\n")
            i=3
            return 'link_error'
    return 'Timeout' #走完循环还没有下载完,即Timeout

此处使用了python request下载文件时,显示进度以及网速的代码。
但是最好加上超时设置,不然很容易会卡死,我的代码部分已经添加在上面的程序一起了。

def gethtml(url,timeout):#超时设置 三次请求
    i = 0
    while i < 3:
        try:
            html = requests.get(url, timeout).text
            return html
        except requests.exceptions.RequestException:
            i += 1
            print('connect timeout')

这里是参考了链接: Python:requests:详解超时和重连.

这里的下载代码要求:

  1. 分块下载,下载大文件有用
  2. 有超时设定,跳过下不动的文件
  3. 异常捕获,避免链接错误程序崩溃
  4. 网络连接检测(我这里还没加上去)

使用正则表达式检索下载链接

将目标网页的内容打开,用正则表达式筛选出其中的下载链接,并将链接写到文本输出。

def Url_matching(url,file_link_list):#挑选目标url的所有链接并输出至txt
    #string要匹配的url内容, file_link_list:输出的文件夹(链接)
    opener = urllib.request.
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值