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:详解超时和重连.
这里的下载代码要求:
- 分块下载,下载大文件有用
- 有超时设定,跳过下不动的文件
- 异常捕获,避免链接错误程序崩溃
- 网络连接检测(我这里还没加上去)
使用正则表达式检索下载链接
将目标网页的内容打开,用正则表达式筛选出其中的下载链接,并将链接写到文本输出。
def Url_matching(url,file_link_list):#挑选目标url的所有链接并输出至txt
#string要匹配的url内容, file_link_list:输出的文件夹(链接)
opener = urllib.request.