1 import time 2 import requests 3 from bs4 import BeautifulSoup 4 #加載一個網頁 5 url='https://ncov.dxy.cn/ncovh5/view/pneumonia?scene=2&clicktime=1579582238&enterid=1579582238&from=singlemessage&isappinstalled=0'#丁香園新型肺炎網頁 6 7 #本機請求頭 8 headers ={ 9 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0' 10 } 11 12 resp=requests.get(url) 13 resp.encoding=resp.apparent_encoding#將網頁返回的字符集類型設置為 自動判斷的字符集類型 14 #print(resp.text) 打印讀取內容 15 #print(resp.encoding)#查看網頁返回的字符集類型 16 #print(resp.apparent_encoding)#自動判斷字符集類型 17 html=resp.text 18 #解析成為beautiful對象 19 soup=BeautifulSoup(html,'html.parser') 20 print('--------------------------------------------------------') 21 #print(soup) 22 #提取數據 23 result=soup.find('body').find('script',{'id':'getAreaStat'}).text 24 print(type(result))#打印出result的數據類型 25 #print(result)#打印到控制台 26 #將數據寫入文件 27 fo=open('result2.txt','w',encoding='utf-8') 28 fo.write(result)#寫入到文件 29 fo.close() 30 #分析文本 31 f = open('result2.txt','r',encoding='utf-8') #由於在當前文件夾下,因此直接寫了文件名 32 for lines in f: 33 ls = lines.strip().replace('try { window.getAreaStat = ','').replace('}catch(e){}','')#將文本中無用信息刪除 34 f.close() 35 list = eval(ls)#將數據文本中數據轉化為list形式 36 print(type(list))#輸出變量list類型 37 print(list)#在控制台打印list 38 time=time.strftime('%Y-%m-%d',time.localtime(time.time()))#獲取當前日期 39 fo=open('{}.txt'.format(time),'w',encoding='utf-8')#最終結果寫入文件,文件名為當前日期 40 fo.write(ls)#寫入到文件 41 fo.close()
運行結果:
文件:
明天准備把數據整理到數據庫中+作詞雲分析