Python3批量下載.dat和.hea檔案
阿新 • • 發佈:2018-11-22
在杭州電子科技大學的讀研的哥哥研究專案需要在一個網站上下載資料進行資料分析,總共4000多份文件資料,若是手工點選連結下載的話,不知道要下載到猴年馬月了,還好我哥知道我會爬蟲,嘿嘿,這時候就該展現我Python爬蟲威力了。
程式碼
#https://physionet.org/physiobank/database/hbedb/BDS00001.dat
import requests
from bs4 import BeautifulSoup
import re
import os
import urllib
def getHTMLText(url):
try :
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return "產生異常"
def getBat(html):
reg = r'href=".*.bat"'
imgre = re.compile(reg)
imglist = re.findall(imgre, html)
return imglist
if __name__== "__main__":
lst=[]
url="https://physionet.org/physiobank/database/hbedb/"
text=getHTMLText(url)
soup=BeautifulSoup(text,"html.parser")
files=soup.find_all('a')
for i in files:
try:
href=i.attrs['href']
lst.append(re.findall(r'BDS.*.hea',href)[0])
except :
continue
for l in lst:
link="https://physionet.org/physiobank/database/hbedb/"+l
ff=requests.get(link)
print(link+"正在下載")
try:
f = open('C:\\Users\\Administrator\\Desktop\\lwf\\Spider\\csdn\\hea\\'+ str(l), 'wb')
f.write(ff.content)
f.close()
except Exception as e:
print("失敗")
效果圖