爬取并处理中国新冠肺炎疫情数据
项⽬名称:
爬取并处理中国新冠肺炎疫情数据
⽬的:
通过Python爬取中国新冠肺炎疫情数据,存⼊Excel,对此数据分析并进⾏可视化,制作查询中国疫情情况的GUI界⾯。
具体内容:
通过Python来实现⼀个爬取并处理中国新冠肺炎疫情数据的爬⾍项⽬,该项⽬能从⽹站获取中国各省最新新冠肺炎疫情数据并将其保存在Excel⽂件中,进⾏数据处理可得到中国疫情累计确诊⼈数前⼗五省的饼状图,该项⽬制作了⼀个可以查询各省各地区新冠肺炎疫情数据的GUI界⾯;
Excel表格设计
饼状图
GUI界⾯
输出设计
系统实现:
本次项⽬使⽤的Python库有:requests,xlwt,json,matplotlib,tkinter,os,re,time
import requests
import os
import re
import xlwt
import time
import json
import matplotlib.pyplot as plt
import tkinter
from tkinter import scrolledtext
from  tkinter  import ttk
from tkinter import*
⼀、爬取数据
代码:
def get_data_html():
headers ={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'}            response = ('ncov.dxy/ncovh5/view/pneumonia?from=timeline&isappinstalled=0', headers=headers, timeout=3) # 请求页⾯
response =t,'utf-8')
# 中⽂重新编码
return response
#返回了HTML数据
def get_data_dictype():
areas_type_dic_raw = re.findall('try { AreaStat = (.*?)}catch\(e\)',get_data_html())
areas_type_dic = json.loads(areas_type_dic_raw[0])
return areas_type_dic
#返回经过json转换过的字典化的数据
处理后得到的数据 areas_type_dic 部分如下图:
由图可看出:
· get_data_dictype() 返回的数据是⼀个列表
· 列表中的每个元素都是⼀个字典,即每个列表元素都是⼀个省的总疫情数据
·
每个字典的provinceName是省份名称,currentConfirmedCount是本省现存确诊⼈数,confirmedCount是本省累计确诊⼈数等等· 每个字典cities键的值是⼀个列表,这个列表的每个元素是字典,包含⼀个地区的疫情数据
⼆、确定及创建项⽬保存路径
若⽂件保存⽬录不存在,则创建此⽬录并输出显⽰“数据⽂件夹不存在”及创建保存的⽬录。数据保存成功则输出显⽰数据爬取成功
代码:
def make_dir():#检查并创建数据⽬录
file_path ='F:/中国疫情情况采集/'
if not ists(file_path):
print('数据⽂件夹不存在')
os.makedirs(file_path)
print('数据⽂件夹创建成功,创建⽬录为%s'%(file_path))
else:
print('数据保存在⽬录:%s'%(file_path))
效果:
三、数据写⼊Excel
Excel形式:
创建多个⼯作表。第⼀个⼯作表命名为“中国各省”,⾥⾯包含各省的新冠肺炎疫情情况(总现存确诊⼈数,总累计确诊⼈数,总疑似⼈数,总治愈⼈数,总死亡⼈数,地区ID编码)。后⾯的⼯作表依次按读取到的省份命名,⼯作表⾥⾯包含的数据为某省具体地区的疫情情况(现存确诊⼈数,累计确诊⼈
数,疑似⼈数,治愈⼈数,死亡⼈数,地区ID编码),第⼆⾏是这个省的总情况,且与本省地区情况之间空⼀⾏,⽅便观察
代码:
def createxcelsheet(workbook,name):
worksheet = workbook.add_sheet(name,cell_overwrite_ok=True) for i in range(0,9):
al = xlwt.Alignment()
al.horz =0x02# 设置⽔平居中
style = xlwt.XFStyle()
style.alignment = al
#写⼊数据列标签
worksheet.write(0,2,'城市名称',style)
worksheet.write(0,3,'现存确诊⼈数',style)
worksheet.write(0,4,'累计确诊⼈数',style)
worksheet.write(0,5,'疑似⼈数',style)
worksheet.write(0,6,'治愈⼈数',style)
worksheet.write(0,7,'死亡⼈数',style)
worksheet.write(0,8,'地区ID编码',style)
return worksheet,style
global label,vvalues #获得中国省份名称和累计确诊⼈数
label=[]
vvalues=[]
def save_data_to_excle():#爬取数据并保存在Excel中
make_dir()#调⽤⽅法检查数据⽬录是否存在,不存在则创建数据⽂件夹    newworkbook = xlwt.Workbook()# 打开⼯作簿,创建⼯作表
sheet,style=createxcelsheet(newworkbook,'中国各省')
count=1#中国各省的计数器
for province_data in get_data_dictype():
c_count=1#某省的计数器
provincename = province_data['provinceName']
provinceshortName = province_data['provinceShortName']
p_currentconfirmedCount=province_data['currentConfirmedCount']
p_confirmedcount = province_data['confirmedCount']
p_suspectedcount = province_data['suspectedCount']
p_curedcount = province_data['curedCount']
p_deadcount = province_data['deadCount']
p_locationid = province_data['locationId']
#⽤循环获取省级以及该省以下城市的数据
label.append(provincename)
vvalues.append( p_confirmedcount)
sheet.write(count,2, provincename,style)
sheet.write(count,3, p_currentconfirmedCount,style)
sheet.write(count,4, p_confirmedcount,style)
sheet.write(count,5, p_suspectedcount,style)
sheet.write(count,6, p_curedcount,style)
sheet.write(count,7, p_deadcount,style)
sheet.write(count,8, p_locationid,style)北京疫情最新数据
count+=1
worksheet,style=createxcelsheet(newworkbook,provincename)
worksheet.write(c_count,2, provinceshortName,style)
worksheet.write(c_count,3, p_currentconfirmedCount,style)
worksheet.write(c_count,4, p_confirmedcount,style)
worksheet.write(c_count,5, p_suspectedcount,style)
worksheet.write(c_count,6, p_curedcount,style)
worksheet.write(c_count,7, p_deadcount,style)
worksheet.write(c_count,8, p_locationid,style)
#在⼯作表⾥写⼊省级数据
c_count+=2#省与省下各城市之间空⼀⾏
for citiy_data in province_data['cities']:
#该部分获取某个省下某城市的数据
cityname = citiy_data['cityName']
c_currentconfirmedCount=citiy_data['currentConfirmedCount']
c_confirmedcount = citiy_data['confirmedCount']
c_suspectedcount = citiy_data['suspectedCount']
c_suspectedcount = citiy_data['suspectedCount']
c_curedcount = citiy_data['curedCount']
c_deadcount = citiy_data['deadCount']
c_locationid = citiy_data['locationId']
#向Excel对应列标写⼊数据
worksheet.write(c_count,2, cityname,style)
worksheet.write(c_count,3, c_currentconfirmedCount,style)
worksheet.write(c_count,4, c_confirmedcount,style)
worksheet.write(c_count,5, c_suspectedcount,style)
worksheet.write(c_count,6, c_curedcount,style)
worksheet.write(c_count,7, c_deadcount,style)
worksheet.write(c_count,8, c_locationid,style)
c_count+=1#此处为写⼊⾏数累加,在cities部分循环
current_time = time.strftime("%Y年%m⽉%d⽇%H:%M:%S", time.localtime())
newworkbook.save('F:\中国疫情情况采集\实时采集-%s.xls'%(current_time))
print('******数据爬取成功******')
效果:
四、绘制饼状图
将各省的累计确诊⼈数数据另取出来,排序到前⼗五名较多⼈数省份⽣成饼状图并保存在⽂件夹中
代码部分解释:
在函数save_data_to_excle中向label列表中顺序添加中国省份名称,向vvalues列表中顺序添加各省累计确诊⼈数。字典z中Label当键,vvalues当值,然后按值逆序排序,之后取前⼗五个。
最后利⽤matplotlib.pyplot中的pie()绘制,title()设置标题,savefig()保存图⽚,show()展⽰图⽚。列表切⽚取前⼗五个。
def sjvisual():
plt.figure(figsize=(7,6))
z=zip(label,vvalues)
s=sorted(z,key=lambda x:x[1],reverse=True)
top15=s[0:15:]
labels=(dict(top15)).keys()
values=(dict(top15)).values()
plt.pie(values,labels=labels,radius =1.2,pctdistance=0.8,autopct='%1.2f%%')#绘制饼图
plt.savefig('F:/中国疫情情况采集/2020年中国疫情确诊⼈数前⼗五省饼图.png')#保存图⽚
plt.show()#展⽰图⽚
五、GUI界⾯
GUI界⾯可查询中国某省总疫情情况和此省下地区的具体疫情情况。通过下拉列表框选择想要查询的省份,若想查询此省下某地区疫情情况,可点击对应地区按钮进⾏查询。
若想查询多个省份,查完⼀个省份后可在下拉列表框中再次选择想要查询的省份,某省下地区疫情情况点击相应按钮即可。
代码:
def GUI():#制作GUI界⾯
global win
win=tkinter.Tk()#构造窗体
win.minsize(800,660)
win.title('中国各省疫情情况查询')
tkinter.Label(win, text ='请选择省份:', height=1, width=10).place(x =200, y =0)
tkinter.Label(win, text ='省份:').place(x =240, y =40)
tkinter.Label(win, text ='现存确诊⼈数:').place(x =240, y =70)
tkinter.Label(win, text ='累计确诊⼈数:').place(x =240, y =100)
tkinter.Label(win, text ='疑似⼈数:').place(x =240, y =130)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。