Python網絡爬蟲——新冠疫情實時數據的爬取與可視化
一、選題背景
按照目前狀況,新冠疫情已成為全國人民極度關注的重點,不管是每日微博熱點還是新聞報告,人們都是非常的關注,不論是瀏覽量還是評論量都是非常高的。由於近幾年大數據行業的蓬勃發展和疫情數據的公開可,數據新聞生產主體的下沉的跡象,更有各大、小眾媒體、個人自媒體開始着手組建專業的數據新聞團隊,通過獲取最新的實時數據,來給新聞增加可讀性,和可信度。除此之外還出現了很多的數據服務的提供商,在不收取任何服務費用下,為互聯網、廣大人民提供數據信息。
自從2020年新冠疫情發生后,至今為止的相關數據新聞已經是非常的巨大了,在每一個重要的事件和時間節點上,都在用數據嘗試幫助我們解剖全球的疫情狀況。由此可見,新冠疫情數據的新聞報道數量與國內疫情發展變化的狀態是基本同步的。為此,本作品是對全國及全球的疫情數據進行實時的爬取,可以更清楚、更直觀地了解到目前疫情全國及全球的發展趨勢。
二、主題式網絡爬蟲方案
1、主題式網絡爬蟲名稱
Python網絡爬蟲——新冠疫情實時數據的爬取與可視化
2、主題是網絡爬蟲爬取的內容與數據特征分析
爬取的內容為(騰訊新聞的新冠病毒疫情的實時追蹤)網址:https://news.qq.com/zt2020/page/feiyan.htm#/
3、主題式網絡爬蟲設計方案概述
第一部分:爬取網站上的全國各地、美國、全球的疫情數據,對數據進行清洗和處理后分別導成Excel表格存儲。
第二部分:對導出的數據進行可視化輸出。(本作品的時間是實時的)
三、主題頁面的結構特征分析
1、主題頁面的結構與特征分析
2、Html頁面解析
3、節點(標簽)查找方法與遍歷方法
四、網絡爬蟲程序設計
1、數據爬取與采集
2、對數據進行清洗和處理
1 import requests 2 import pandas as pd 3 import json 4 import time 5 from IPython.display import display, HTML # 可以輸出正確的表格樣式 6 7 # 觀察開發者工具network找到url 8 int_url = 'https://api.inews.qq.com/newsqa/v1/automation/foreign/country/ranklist' 9 # 找到顯示國內疫情數據的url,如: 10 # 'https://panshi.qq.com/v2/vote/23311878?source=1&callback=jQuery35105457093859854443_1624342555735&_=1624342555736' 11 # 'jQuery35105457093859854443_1624342555735'可省略不寫,其后面的數字為time.time()*1000,按照其格式構造url,即實時數據的url 12 cn_url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_=%d' % int(time.time() * 1000) 13 usa_url = 'https://api.inews.qq.com/newsqa/v1/automation/foreign/daily/list?country=美國&=' 14 china_url = 'https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=chinaDayList,chinaDayAddList,nowConfirmStatis,provinceCompare'
1 def get_int_page(page_int): # 請求世界各國疫情數據 2 try: 3 response = requests.get(url=page_int) 4 if response.status_code == 200: 5 return response.json()['data'] 6 except requests.exceptions.ConnectionError as e: 7 print('Error', e.args) 8 9 10 def get_cn_page(page_cn): # 請求中國疫情數據 11 try: 12 resp = requests.get(url=page_cn) 13 if resp.status_code == 200: 14 return json.loads(resp.json()['data']) 15 except requests.exceptions.ConnectionError as e: 16 print('Error', e.args) 17 18 19 def get_usa_page(page_usa): # 請求美國每日疫情數據 20 try: 21 response = requests.get(url=page_usa) 22 if response.status_code == 200: 23 return response.json()['data'][453:-2] 24 except requests.exceptions.ConnectionError as e: 25 print('Error', e.args) 26 27 28 def get_china_page(page_china): # 請求中國每日疫情數據 29 try: 30 response = requests.get(url=page_china) 31 if response.status_code == 200: 32 return response.json()['data'] 33 except requests.exceptions.ConnectionError as e: 34 print('Error', e.args)
1 def parse_int_page(items_int): # 解析世界各國疫情數據,並返回一個數據列表用於之后構造DataFrame 2 data_int = [] 3 for item_int in items_int: 4 int_country = item_int.get('name') # 國家 5 int_confirm = item_int.get('confirm') # 累計確診人數 6 int_dead = item_int.get('dead') # 累計死亡人數 7 int_heal = item_int.get('heal') # 累計治愈人數 8 int_nowConfirm = item_int.get('nowConfirm') # 現有確診人數 9 int_confirm_add = item_int.get('confirmAdd') # 新增確診人數 10 int_healCompare = item_int.get('healCompare') # 新增治愈人數 11 int_deadCompare = item_int.get('deadCompare') # 新增死亡人數 12 year = item_int.get('y') # 當前年 13 month, day = item_int.get('date').split('.') # 當前月,日 14 int_date = year + '-' + month + '-' + day 15 dic = {'國家': int_country, '日期 ': int_date, '累計確診': int_confirm, 16 '累計死亡': int_dead, '累計治愈': int_heal, '現有確診': int_nowConfirm, 17 '當日新增確診': int_confirm_add, '當日新增治愈': int_healCompare, '當日新增死亡': int_deadCompare} 18 data_int.append(dic) 19 return data_int 20 21 22 def parse_cn_page(items_cn): # 解析中國疫情數據,將中國的數據加入到世界各國數據的DataFrame中,並且構造每個省的DataFrame 23 cn_date = items_cn['lastUpdateTime'].split(' ')[0] # 當前日期 24 cn_confirm = items_cn['chinaTotal']['confirm'] # 累計確診 25 cn_dead = items_cn['chinaTotal']['dead'] # 累計死亡 26 cn_heal = items_cn['chinaTotal']['heal'] # 累計治愈 27 cn_nowConfirm = items_cn['chinaTotal']['nowConfirm'] # 現有確診(輸入型+本地) 28 cn_confirm_add = items_cn['chinaAdd']['confirm'] # 當日新增確診 29 cn_healCompare = items_cn['chinaAdd']['heal'] # 當日新增治愈 30 cn_deadCompare = items_cn['chinaAdd']['dead'] # 當日新增死亡 31 cn_list = ['中國', cn_date, cn_confirm, 32 cn_dead, cn_heal, cn_nowConfirm, 33 cn_confirm_add, cn_healCompare, cn_deadCompare] 34 return cn_list 35 36 37 def parse_province_page(items_cn): # 解析中國各省疫情數據 38 province_list = [] 39 province_items = items_cn['areaTree'][0]['children'] 40 for province_item in province_items: 41 province_name = province_item['name'] # 省份 42 province_date = items_cn['lastUpdateTime'].split(' ')[0] # 當前日期 43 province_confirm = province_item['total']['confirm'] # 累計確診 44 province_dead = province_item['total']['dead'] # 累計死亡 45 province_heal = province_item['total']['heal'] # 累計治愈 46 province_nowConfirm = province_item['total']['nowConfirm'] # 現有確診 47 province_confirm_add = province_item['today']['confirm'] # 當日新增確診 48 healRate = province_item['total']['healRate'] # 治愈率 49 deadRate = province_item['total']['deadRate'] # 死亡率 50 province_dic = {'省份': province_name, '日期': province_date, 51 '累計確診': province_confirm, '累計死亡': province_dead, 52 '累計治愈': province_heal, '現有確診': province_nowConfirm, 53 '當日新增確診': province_confirm_add, '治愈率': healRate, '死亡率': deadRate} 54 province_list.append(province_dic) 55 return province_list 56 57 58 def parse_usa_page(items_usa): # 解析美國每日疫情數據 59 usa_list = [] 60 for item_usa in items_usa: 61 year = item_usa['y'] 62 month, day = item_usa['date'].split('.') 63 date = year + '-' + month + '-' + day 64 usa_confirm_add = item_usa['confirm_add'] 65 usa_confirm = item_usa['confirm'] 66 usa_heal = item_usa['heal'] 67 usa_dead = item_usa['dead'] 68 usa_dic = {'日期': date, '當日新增': usa_confirm_add, '累計確診': usa_confirm, '累計治愈': usa_heal, '累計死亡': usa_dead} 69 usa_list.append(usa_dic) 70 return usa_list 71 72 73 def parse_china_page(items_china): # 解析中國每日疫情數據 74 china_list = [] 75 item_dayadds = items_china['chinaDayAddList'] 76 item_days = items_china['chinaDayList'] 77 for item_dayadd, item_day in zip(item_dayadds, item_days): 78 year = item_dayadd['y'] 79 month, day = item_dayadd['date'].split('.') 80 date = year + '-' + month + '-' + day 81 china_confirm_add = item_dayadd['confirm'] 82 china_confirm = item_day['confirm'] 83 china_heal = item_day['heal'] 84 china_dead = item_day['dead'] 85 china_dic = {'日期': date, '當日新增': china_confirm_add, '累計確診': china_confirm, 86 '累計治愈': china_heal, '累計死亡': china_dead} 87 china_list.append(china_dic) 88 return china_list
1 def set_up_table(data, cn, province, usa, china): # 創建修改DataFrame 2 int_df = pd.DataFrame(data) 3 int_df.index = range(1, 186) 4 int_df.loc[0] = cn 5 int_df = int_df.sort_index(ascending=True) 6 province_df = pd.DataFrame(province) 7 usa_df = pd.DataFrame(usa) 8 china_df = pd.DataFrame(china) 9 return int_df, province_df, usa_df, china_df 10 11 12 def write_table(data1, data2, data3, data4): # 存儲表 13 data1.to_excel('世界疫情數據.xlsx', encoding='utf-8') 14 data2.to_excel('中國各省疫情數據.xlsx', encoding='utf-8') 15 data3.to_excel('美國每日疫情數據.xlsx', encoding='utf-8') 16 data4.to_excel('中國每日疫情數據.xlsx', encoding='utf-8') 17 print('已存儲')
1 def main(): 2 int_data = get_int_page(int_url) 3 cn_data = get_cn_page(cn_url) 4 usa_data = get_usa_page(usa_url) 5 china_data = get_china_page(china_url) 6 c_list = parse_cn_page(cn_data) 7 p_list = parse_province_page(cn_data) 8 list_data_int = parse_int_page(int_data) 9 u_list = parse_usa_page(usa_data) 10 cn_list = parse_china_page(china_data) 11 # display(set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[3]) # 若直接print,則輸出的不是表格 12 write_table(set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[0], 13 set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[1], 14 set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[2], 15 set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[3],) 16 17 if __name__ == '__main__': 18 main()
分別查看一下每份爬取的數據
首先我們要知道,因為25日還沒過,但是為了統一方便觀察都做成25日的數據,所以要知道數據是從24日的24點至25日19:36分(也就是目前運行程序的時間)的實時數據。(各部分沒更新的國家例外)
世界疫情數據:
(注意觀察美國的數據)
中國各省疫情數據
美國每日疫情數據
(這里爬取的是近兩個月內美國的數據)
這里我們可以看到目前美國只更新到23日,其中所有的數據都是沒有更新的,所以可以發現前面世界疫情數據的表格中,美國的數據是沒有個更新的,只更新到了23日。
所以這里可以看出是美國那邊更新的問題。
中國每日疫情數據
(同樣為了比較爬取的也是近兩個月中國的數據)
4、數據分析與可視化
1 import matplotlib.pyplot as plt 2 import numpy as np 3 %matplotlib inline 4 plt.rcParams['font.sans-serif'] = ['SimHei'] 5 import datetime
1 int_df = pd.read_excel('世界疫情數據.xlsx') 2 cn_province_df = pd.read_excel('中國各省疫情數據.xlsx') 3 usa_df = pd.read_excel('美國每日疫情數據.xlsx') 4 china_df = pd.read_excel('中國每日疫情數據.xlsx') 5 int_df = int_df.drop('Unnamed: 0',axis=1) 6 cn_province_df = cn_province_df.drop('Unnamed: 0',axis=1) 7 usa_df = usa_df.drop('Unnamed: 0',axis=1) 8 china_df = china_df.drop('Unnamed: 0',axis=1)
世界累計確診人數top前20的國家與中國的對比柱狀圖
1 int_top20 = int_df.head(21) # 取出中國及前20個國家的數據 2 # 作圖: 3 plt.title('截止' + int_top20['日期 '][0] + '的累計確診人數和累計死亡人數') 4 5 # plt.xlabel('國家') 6 # plt.ylabel('人數') 7 x = int_top20['國家'] 8 y = int_top20['累計確診'] 9 10 # plt.ylim(0, max(int_top20['累計確診'])) 11 plt.xticks(rotation=65) 12 plt.bar(range(len(x)), y,color='r',tick_label=x) 13 14 plt.show()
世界確診人數top5國家與中國對比子圖
1 int_top5 = int_df.head(6) 2 # 作圖 3 x = int_top5['國家'] 4 5 plt.subplot(2,2,1) 6 plt.title('截止' + int_top5['日期 '][0] + '的累計確診人數') 7 plt.ylabel('人數') 8 y1 = int_top5['累計確診'] 9 plt.ylim(0, max(int_top5['累計確診'])) 10 plt.xticks(rotation=65) 11 plt.bar(range(len(x)), y1,color='c',tick_label=x) 12 13 plt.subplot(2,2,2) 14 plt.title('截止' + int_top5['日期 '][0] + '的累計死亡人數') 15 plt.ylabel('人數') 16 y2 = int_top5['累計死亡'] 17 plt.ylim(0, max(int_top5['累計死亡'])) 18 plt.xticks(rotation=65) 19 plt.bar(range(len(x)), y2,color='violet',tick_label=x) 20 21 plt.subplot(2,2,3) 22 plt.title('截止' + int_top5['日期 '][0] + '的累計治愈人數') 23 plt.ylabel('人數') 24 y3 = int_top5['累計治愈'] 25 plt.ylim(0, max(int_top5['累計治愈'])) 26 plt.xticks(rotation=65) 27 plt.bar(range(len(x)), y3,color='cornflowerblue',tick_label=x) 28 29 plt.subplot(2,2,4) 30 plt.title(int_top5['日期 '][0] + '新增確診') 31 plt.ylabel('人數') 32 y4 = int_top5['當日新增確診'] 33 plt.ylim(0, max(int_top5['當日新增確診'])) 34 plt.xticks(rotation=65) 35 plt.bar(range(len(x)), y4,color='black',tick_label=x) 36 37 plt.subplots_adjust(wspace =0.5, hspace = 1) 38 plt.show()
各省累計確診人數top20統計柱狀圖
1 i = datetime.datetime.now() 2 plt.title(str('%s'%i)[:16] + '的累計確診人數') 3 4 label_list = cn_province_df.head(20)['省份'] 5 x = range(len(cn_province_df.head(20)['省份'])) 6 y = cn_province_df.head(20)['累計確診'] 7 8 plt.ylim(0, max(cn_province_df.head(20)['累計確診'])) 9 plt.xticks(rotation=90) 10 11 plt.bar(x=x, height=y, width=0.6, alpha=0.8, color='c') 12 plt.ylim(0, 70000) 13 plt.ylabel('人數') 14 plt.xticks([index + 0.2 for index in x], label_list, rotation=65) 15 16 17 plt.show()
累計死亡top10各省死亡率餅圖
1 plt.title('死亡率') 2 plt.pie(labels=cn_province_df.head(10)['省份'] ,x=cn_province_df.head(10)['死亡率'],colors=['b','r','yellow','c','orange','lime']) 3 plt.show()
5、根據數據之間的關系,分析兩個變量之間的相關系數,畫出散點圖。
中美近兩個月疫情對比(2021.4.23起)
1 x = np.arange(1,len(china_df['日期'])+1) 2 y1 = usa_df['當日新增'] 3 y2 = china_df['當日新增'] 4 plt.figure(figsize=(12,8)) 5 plt.title('中美每日新增') 6 plt.xlabel('天數') 7 plt.ylabel('數量') 8 s1 = plt.plot(x,y1,marker='o',label='美國',color='r' ) # 繪制圖形 9 s2 = plt.plot(x,y2,marker='o',label='中國',color='c') 10 plt.xticks(x) 11 plt.legend() 12 plt.show()
1 usa_df.head()
1 x = np.arange(1,len(china_df['日期'])+1) 2 y1 = usa_df['累計確診'] 3 y2 = china_df['累計確診'] 4 plt.figure(figsize=(12,8)) 5 plt.title('中美累計確診') 6 plt.xlabel('天數') 7 plt.ylabel('數量') 8 s1 = plt.plot(x,y1,marker='o',label='美國',color='black' ) # 繪制圖形 9 s2 = plt.plot(x,y2,marker='o',label='中國',color='red') 10 plt.xticks(x) 11 plt.legend() 12 plt.show()
7、附上完整程序代碼
1 import requests 2 import pandas as pd 3 import json 4 import time 5 from IPython.display import display, HTML # 可以輸出正確的表格樣式 6 7 # 觀察開發者工具network找到url 8 int_url = 'https://api.inews.qq.com/newsqa/v1/automation/foreign/country/ranklist' 9 # 找到顯示國內疫情數據的url,如: 10 # 'https://panshi.qq.com/v2/vote/23311878?source=1&callback=jQuery35105457093859854443_1624342555735&_=1624342555736' 11 # 'jQuery35105457093859854443_1624342555735'可省略不寫,其后面的數字為time.time()*1000,按照其格式構造url,即實時數據的url 12 cn_url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_=%d' % int(time.time() * 1000) 13 usa_url = 'https://api.inews.qq.com/newsqa/v1/automation/foreign/daily/list?country=美國&=' 14 china_url = 'https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=chinaDayList,chinaDayAddList,nowConfirmStatis,provinceCompare' 15 def get_int_page(page_int): # 請求世界各國疫情數據 16 try: 17 response = requests.get(url=page_int) 18 if response.status_code == 200: 19 return response.json()['data'] 20 except requests.exceptions.ConnectionError as e: 21 print('Error', e.args) 22 23 24 def get_cn_page(page_cn): # 請求中國疫情數據 25 try: 26 resp = requests.get(url=page_cn) 27 if resp.status_code == 200: 28 return json.loads(resp.json()['data']) 29 except requests.exceptions.ConnectionError as e: 30 print('Error', e.args) 31 32 33 def get_usa_page(page_usa): # 請求美國每日疫情數據 34 try: 35 response = requests.get(url=page_usa) 36 if response.status_code == 200: 37 return response.json()['data'][453:-2] 38 except requests.exceptions.ConnectionError as e: 39 print('Error', e.args) 40 41 42 def get_china_page(page_china): # 請求中國每日疫情數據 43 try: 44 response = requests.get(url=page_china) 45 if response.status_code == 200: 46 return response.json()['data'] 47 except requests.exceptions.ConnectionError as e: 48 print('Error', e.args) 49 def parse_int_page(items_int): # 解析世界各國疫情數據,並返回一個數據列表用於之后構造DataFrame 50 data_int = [] 51 for item_int in items_int: 52 int_country = item_int.get('name') # 國家 53 int_confirm = item_int.get('confirm') # 累計確診人數 54 int_dead = item_int.get('dead') # 累計死亡人數 55 int_heal = item_int.get('heal') # 累計治愈人數 56 int_nowConfirm = item_int.get('nowConfirm') # 現有確診人數 57 int_confirm_add = item_int.get('confirmAdd') # 新增確診人數 58 int_healCompare = item_int.get('healCompare') # 新增治愈人數 59 int_deadCompare = item_int.get('deadCompare') # 新增死亡人數 60 year = item_int.get('y') # 當前年 61 month, day = item_int.get('date').split('.') # 當前月,日 62 int_date = year + '-' + month + '-' + day 63 dic = {'國家': int_country, '日期 ': int_date, '累計確診': int_confirm, 64 '累計死亡': int_dead, '累計治愈': int_heal, '現有確診': int_nowConfirm, 65 '當日新增確診': int_confirm_add, '當日新增治愈': int_healCompare, '當日新增死亡': int_deadCompare} 66 data_int.append(dic) 67 return data_int 68 69 70 def parse_cn_page(items_cn): # 解析中國疫情數據,將中國的數據加入到世界各國數據的DataFrame中,並且構造每個省的DataFrame 71 cn_date = items_cn['lastUpdateTime'].split(' ')[0] # 當前日期 72 cn_confirm = items_cn['chinaTotal']['confirm'] # 累計確診 73 cn_dead = items_cn['chinaTotal']['dead'] # 累計死亡 74 cn_heal = items_cn['chinaTotal']['heal'] # 累計治愈 75 cn_nowConfirm = items_cn['chinaTotal']['nowConfirm'] # 現有確診(輸入型+本地) 76 cn_confirm_add = items_cn['chinaAdd']['confirm'] # 當日新增確診 77 cn_healCompare = items_cn['chinaAdd']['heal'] # 當日新增治愈 78 cn_deadCompare = items_cn['chinaAdd']['dead'] # 當日新增死亡 79 cn_list = ['中國', cn_date, cn_confirm, 80 cn_dead, cn_heal, cn_nowConfirm, 81 cn_confirm_add, cn_healCompare, cn_deadCompare] 82 return cn_list 83 84 85 def parse_province_page(items_cn): # 解析中國各省疫情數據 86 province_list = [] 87 province_items = items_cn['areaTree'][0]['children'] 88 for province_item in province_items: 89 province_name = province_item['name'] # 省份 90 province_date = items_cn['lastUpdateTime'].split(' ')[0] # 當前日期 91 province_confirm = province_item['total']['confirm'] # 累計確診 92 province_dead = province_item['total']['dead'] # 累計死亡 93 province_heal = province_item['total']['heal'] # 累計治愈 94 province_nowConfirm = province_item['total']['nowConfirm'] # 現有確診 95 province_confirm_add = province_item['today']['confirm'] # 當日新增確診 96 healRate = province_item['total']['healRate'] # 治愈率 97 deadRate = province_item['total']['deadRate'] # 死亡率 98 province_dic = {'省份': province_name, '日期': province_date, 99 '累計確診': province_confirm, '累計死亡': province_dead, 100 '累計治愈': province_heal, '現有確診': province_nowConfirm, 101 '當日新增確診': province_confirm_add, '治愈率': healRate, '死亡率': deadRate} 102 province_list.append(province_dic) 103 return province_list 104 105 106 def parse_usa_page(items_usa): # 解析美國每日疫情數據 107 usa_list = [] 108 for item_usa in items_usa: 109 year = item_usa['y'] 110 month, day = item_usa['date'].split('.') 111 date = year + '-' + month + '-' + day 112 usa_confirm_add = item_usa['confirm_add'] 113 usa_confirm = item_usa['confirm'] 114 usa_heal = item_usa['heal'] 115 usa_dead = item_usa['dead'] 116 usa_dic = {'日期': date, '當日新增': usa_confirm_add, '累計確診': usa_confirm, '累計治愈': usa_heal, '累計死亡': usa_dead} 117 usa_list.append(usa_dic) 118 return usa_list 119 120 121 def parse_china_page(items_china): # 解析中國每日疫情數據 122 china_list = [] 123 item_dayadds = items_china['chinaDayAddList'] 124 item_days = items_china['chinaDayList'] 125 for item_dayadd, item_day in zip(item_dayadds, item_days): 126 year = item_dayadd['y'] 127 month, day = item_dayadd['date'].split('.') 128 date = year + '-' + month + '-' + day 129 china_confirm_add = item_dayadd['confirm'] 130 china_confirm = item_day['confirm'] 131 china_heal = item_day['heal'] 132 china_dead = item_day['dead'] 133 china_dic = {'日期': date, '當日新增': china_confirm_add, '累計確診': china_confirm, 134 '累計治愈': china_heal, '累計死亡': china_dead} 135 china_list.append(china_dic) 136 return china_list 137 def set_up_table(data, cn, province, usa, china): # 創建修改DataFrame 138 int_df = pd.DataFrame(data) 139 int_df.index = range(1, 186) 140 int_df.loc[0] = cn 141 int_df = int_df.sort_index(ascending=True) 142 province_df = pd.DataFrame(province) 143 usa_df = pd.DataFrame(usa) 144 china_df = pd.DataFrame(china) 145 return int_df, province_df, usa_df, china_df 146 147 148 def write_table(data1, data2, data3, data4): # 存儲表 149 data1.to_excel('世界疫情數據.xlsx', encoding='utf-8') 150 data2.to_excel('中國各省疫情數據.xlsx', encoding='utf-8') 151 data3.to_excel('美國每日疫情數據.xlsx', encoding='utf-8') 152 data4.to_excel('中國每日疫情數據.xlsx', encoding='utf-8') 153 print('已存儲') 154 def main(): 155 int_data = get_int_page(int_url) 156 cn_data = get_cn_page(cn_url) 157 usa_data = get_usa_page(usa_url) 158 china_data = get_china_page(china_url) 159 c_list = parse_cn_page(cn_data) 160 p_list = parse_province_page(cn_data) 161 list_data_int = parse_int_page(int_data) 162 u_list = parse_usa_page(usa_data) 163 cn_list = parse_china_page(china_data) 164 # display(set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[3]) # 若直接print,則輸出的不是表格 165 write_table(set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[0], 166 set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[1], 167 set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[2], 168 set_up_table(list_data_int, c_list, p_list, u_list, cn_list)[3],) 169 170 if __name__ == '__main__': 171 main() 172 import matplotlib.pyplot as plt 173 import numpy as np 174 %matplotlib inline 175 plt.rcParams['font.sans-serif'] = ['SimHei'] 176 import datetime 177 int_df = pd.read_excel('世界疫情數據.xlsx') 178 cn_province_df = pd.read_excel('中國各省疫情數據.xlsx') 179 usa_df = pd.read_excel('美國每日疫情數據.xlsx') 180 china_df = pd.read_excel('中國每日疫情數據.xlsx') 181 int_df = int_df.drop('Unnamed: 0',axis=1) 182 cn_province_df = cn_province_df.drop('Unnamed: 0',axis=1) 183 usa_df = usa_df.drop('Unnamed: 0',axis=1) 184 china_df = china_df.drop('Unnamed: 0',axis=1) 185 int_top20 = int_df.head(21) # 取出中國及前20個國家的數據 186 # 作圖: 187 plt.title('截止' + int_top20['日期 '][0] + '的累計確診人數和累計死亡人數') 188 189 # plt.xlabel('國家') 190 # plt.ylabel('人數') 191 x = int_top20['國家'] 192 y = int_top20['累計確診'] 193 194 # plt.ylim(0, max(int_top20['累計確診'])) 195 plt.xticks(rotation=65) 196 plt.bar(range(len(x)), y,color='r',tick_label=x) 197 198 plt.show() 199 int_top5 = int_df.head(6) 200 # 作圖 201 x = int_top5['國家'] 202 203 plt.subplot(2,2,1) 204 plt.title('截止' + int_top5['日期 '][0] + '的累計確診人數') 205 plt.ylabel('人數') 206 y1 = int_top5['累計確診'] 207 plt.ylim(0, max(int_top5['累計確診'])) 208 plt.xticks(rotation=65) 209 plt.bar(range(len(x)), y1,color='c',tick_label=x) 210 211 plt.subplot(2,2,2) 212 plt.title('截止' + int_top5['日期 '][0] + '的累計死亡人數') 213 plt.ylabel('人數') 214 y2 = int_top5['累計死亡'] 215 plt.ylim(0, max(int_top5['累計死亡'])) 216 plt.xticks(rotation=65) 217 plt.bar(range(len(x)), y2,color='violet',tick_label=x) 218 219 plt.subplot(2,2,3) 220 plt.title('截止' + int_top5['日期 '][0] + '的累計治愈人數') 221 plt.ylabel('人數') 222 y3 = int_top5['累計治愈'] 223 plt.ylim(0, max(int_top5['累計治愈'])) 224 plt.xticks(rotation=65) 225 plt.bar(range(len(x)), y3,color='cornflowerblue',tick_label=x) 226 227 plt.subplot(2,2,4) 228 plt.title(int_top5['日期 '][0] + '新增確診') 229 plt.ylabel('人數') 230 y4 = int_top5['當日新增確診'] 231 plt.ylim(0, max(int_top5['當日新增確診'])) 232 plt.xticks(rotation=65) 233 plt.bar(range(len(x)), y4,color='black',tick_label=x) 234 235 plt.subplots_adjust(wspace =0.5, hspace = 1) 236 plt.show() 237 cn_province_df = cn_province_df.sort_values('累計確診', ascending=False) # 以累計確診數降序排序 238 i = datetime.datetime.now() 239 plt.title(str('%s'%i)[:16] + '的累計確診人數') 240 241 label_list = cn_province_df.head(20)['省份'] 242 x = range(len(cn_province_df.head(20)['省份'])) 243 y = cn_province_df.head(20)['累計確診'] 244 245 plt.ylim(0, max(cn_province_df.head(20)['累計確診'])) 246 plt.xticks(rotation=90) 247 248 plt.bar(x=x, height=y, width=0.6, alpha=0.8, color='c') 249 plt.ylim(0, 70000) 250 plt.ylabel('人數') 251 plt.xticks([index + 0.2 for index in x], label_list, rotation=65) 252 253 254 plt.show() 255 plt.title('死亡率') 256 plt.pie(labels=cn_province_df.head(10)['省份'] ,x=cn_province_df.head(10)['死亡率'],colors=['b','r','yellow','c','orange','lime']) 257 plt.show() 258 x = np.arange(1,len(china_df['日期'])+1) 259 y1 = usa_df['當日新增'] 260 y2 = china_df['當日新增'] 261 plt.figure(figsize=(12,8)) 262 plt.title('中美每日新增') 263 plt.xlabel('天數') 264 plt.ylabel('數量') 265 s1 = plt.plot(x,y1,marker='o',label='美國',color='r' ) # 繪制圖形 266 s2 = plt.plot(x,y2,marker='o',label='中國',color='c') 267 plt.xticks(x) 268 plt.legend() 269 plt.show() 270 usa_df.head() 271 x = np.arange(1,len(china_df['日期'])+1) 272 y1 = usa_df['累計確診'] 273 y2 = china_df['累計確診'] 274 plt.figure(figsize=(12,8)) 275 plt.title('中美累計確診') 276 plt.xlabel('天數') 277 plt.ylabel('數量') 278 s1 = plt.plot(x,y1,marker='o',label='美國',color='black' ) # 繪制圖形 279 s2 = plt.plot(x,y2,marker='o',label='中國',color='red') 280 plt.xticks(x) 281 plt.legend() 282 plt.show()
五、總結
1.經過對主題數據的分析與可視化,可以得到哪些結論?是否達到預期的目標?
扇形圖顯示我國湖北的死亡率占比較大百分比,柱狀圖顯示湖北累計確診人數最高,可見湖北是我國高風險地區,通過中美兩國的每日確診折線圖對比,可以看出中國在疫情的防范和控制做的相對好,沒有過大的波動,處於一個穩定的控制狀態,我相信中國是可以扛過這次的疫情的。通過本次的疫情數據爬取實時數據項目,確實已經達到了實時數據的預期目標。
2.在完成此設計過程中,得到哪些收獲?以及要改進的建議?
通過本次的疫情實時數據爬取及可視化的項目,我明白了再做一個項目時,不應該着急的去敲代碼,而是應該先做好需求分析,了解技術難點,這樣才能選擇需要的技術方法,框架。