说明: 本文是Python可视化技术结合时下热点进行进行开发、讲解的案例,也课程思政的一个形式。文章遵守CSDN平台规定和国家法规(非新闻资质的网站不允许发布疫情数据),对运行结果(2020年2月8日)中涉及数据部分进行屏蔽,同时删除提供数据的网站链接。
请参考本人其他两篇中的抓包分析过程
用Python抓新型冠状病毒肺炎实时数据,绘制市内疫情地图
用Python抓新型冠状病毒肺炎疫情数据,绘制全国疫情分布图
#%%
import time, json, requests
import jsonpath
from pyecharts.charts import Map
import pyecharts.options as opts
#%%
# 全国疫情地区分布(各省确诊病例)
def catch_cn_disease_dis():
timestamp = '%d'%int(time.time()*1000)
url_area = ('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
'&callback=&_=') + timestamp
world_data = json.loads(requests.get(url=url_area).json()['data'])
china_data = jsonpath.jsonpath(world_data,
expr='$.areaTree[0].children[*]')
ls_province_names = jsonpath.jsonpath(china_data, expr='$[*].name')
ls_confirm_vals = jsonpath.jsonpath(china_data, expr='$[*].total.confirm')
ls_province_confirm = list(zip(ls_province_names, ls_confirm_vals,))
return ls_province_confirm, world_data
#%%
ls_province_cfm, dic_world_data = catch_cn_disease_dis()
print(ls_province_cfm)
#%%
# 绘制全国疫情地图
def map_cn_disease_dis() -> Map:
c = (
Map()
.add('中国', ls_province_cfm, 'china')
.set_global_opts(
title_opts=opts.TitleOpts(title='全国新型冠状病毒疫情地图(确诊数)'),
visualmap_opts=opts.VisualMapOpts(is_show=True,
split_number=6,
is_piecewise=True, # 是否为分段型
pos_top='center',
pieces=[
{'min': 10000, 'color': '#7f1818'}, #不指定 max
{'min': 1000, 'max': 10000},
{'min': 500, 'max': 999},
{'min': 100, 'max': 499},
{'min': 10, 'max': 99},
{'min': 0, 'max': 5} ],
),
)
)
return c
map_cn_disease_dis().render('全国疫情地图.html')
# 获取福建省确诊分布数据
def catch_fj_disease_dis():
dic_world_data = catch_cn_disease_dis()[1]
dic_fj_cfm = dict()
# 解析福建各个城市的数据
dic_fj = jsonpath.jsonpath(dic_world_data,
expr='$.areaTree[0].children[?(@.name=="福建")].children[*]')
for item in dic_fj:
if item['name'] not in dic_fj_cfm:
dic_fj_cfm.update({item['name']:0})
dic_fj_cfm[item['name']] += int(item['total']['confirm'])
return dic_fj_cfm
dic_fj_cfm = catch_fj_disease_dis()
#%%
# 绘制福建省疫情地图
def map_fj_disease_dis() -> Map:
# dic_fj_cfm = catch_fj_disease_dis
ls_fj_cities = [name + '市' for name in dic_fj_cfm.keys()]
c = (
Map()
.add('福建省', [list(z) for z in zip(ls_fj_cities, dic_fj_cfm.values())], '福建')
.set_series_opts(label_opts=opts.LabelOpts(is_show=True, formatter='{b}\n{c}例'))
.set_global_opts(
title_opts=opts.TitleOpts(title='福建新型冠状病毒疫情地图(确诊数)'),
visualmap_opts=opts.VisualMapOpts(is_show=True,
split_number=6,
is_piecewise=True, # 是否为分段型
pos_top='center',
pieces=[
{'min': 50},
{'min': 30, 'max': 49},
{'min': 20, 'max': 29},
{'min': 10, 'max': 19},
{'min': 1, 'max': 9},
{'value': 0, "label": '无确诊病例', "color": 'green'} ],
),
)
)
return c
map_fj_disease_dis().render('福建疫情地图.html')
from pyquery import PyQuery as pq
from bs4 import BeautifulSoup
import datetime
import numpy as np
import re
# 获取福建省疾病预防控制中心官网疫情通告列表
def catch_fz_disease_rpt_list() -> str:
session = requests.session()
crawl_timestamp = int(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)
keyword = {'txtkeyword':'福建省新增新型冠状病毒感染的肺炎疫情情况'}
html = ''
while True:
try:
rsp = session.get('http://www.fjcdc.com.cn/search', params=keyword)
except requests.exceptions.ChunkedEncodingError:
continue
rsp.raise_for_status() # 非200则抛出异常(rsp.status_code != 200)
html = rsp.content
break
return html
#%%
html = catch_fz_disease_rpt_list()
#%%
# 获取最新一期的疫情通告链接地址
def catch_fz_disease_latest_rpt():
# html = catch_fz_disease_rpt_list()
doc = pq(html)
# 方法一:第一条数据,doc('.list li a').attr.href即可得到所要链接
# 方法二:指定日期, doc('.list li:contains("2020-02-02") a').attr.href
# 但是这里咱们多写点,练习嘛,乱写
news = doc('.list li').items()
dates = []
for item in news:
date_str = item('span').text().strip()
date = datetime.datetime.strptime(date_str,'%Y-%m-%d')
dates.append(date)
temp = np.array(dates)
latest_date = temp.max()
latest_date_str = latest_date.strftime('%Y-%m-%d')
latest_date_url = doc('.list li:contains("{0}") a'.format(latest_date_str)).attr.href
latest_date_url = 'http://www.fjcdc.com.cn' + latest_date_url
return latest_date_url
#%%
print(catch_fz_disease_latest_rpt())
#%%
# 解析网页,获取确诊和疑似病例数据文本
def catch_fz_disease_dis():
latest_date_url = catch_fz_disease_latest_rpt()
soup = ''
while True:
try:
rsp = requests.session().get(latest_date_url)
except requests.exceptions.ChunkedEncodingError:
continue
rsp.raise_for_status() # 非200则抛出异常(rsp.status_code != 200)
soup = BeautifulSoup(rsp.content, 'lxml')
# print(soup)
break
reg = re.compile('.*福州市.*')
soup = soup.find('div', class_='showCon')
tag = soup.find_all(text=reg)
if len(tag) != 4:
raise Exception('查找到值的次数必须等于 4. 实际值为: {}'.format(len(tag)))
area_data = {}
# area_data.update({'confirm_added':tag[0]})
# area_data.update({'suspend_added':tag[1]})
area_data.update({'confirm':tag[2]})
area_data.update({'suspend':tag[3]})
return area_data
#%%
fz_data = catch_fz_disease_dis()
print(fz_data)
#%%
import re
# 解析各区县数据
def exact_towns_dis():
# fz_data = catch_fz_disease_dis()
pattern = re.compile('(?<=、|()\D+[市|县|区]\d+例')
town_list = pattern.findall(fz_data['confirm'])
# town_list = fz_data['confirm'].split('(|(')[1].split('))')[0].split('、')
# 平潭单列,不处理
town_data = {'福州市区':0}
for town in town_list:
match_num = re.search(r'\d+(?=例)', town)
match_town_name = re.search(r'\D+[市|县|区]', town)
if match_num and town:
match_num = int(match_num.group())
match_town_name = match_town_name.group()
else:
continue
if match_town_name == '长乐区': # 地图中长乐为市
match_town_name = '长乐市'
town_data.update({match_town_name: match_num})
# 晋安、鼓楼、马尾、仓山、台江
if match_town_name[-1] == '区' :
town_data['福州市区'] += match_num
return town_data
#%%
fz_town_data = exact_towns_dis()
print(fz_town_data)
#%%
from pyecharts.commons.utils import JsCode
def map_fz_disease_dis() -> Map:
# fz_town_data = exact_towns_dis()
# ls_fz_towns = [name + '市' for name in fz_town_data.keys()]
c = (
Map()
.add('福州市(不含平潭)', [list(z) for z in zip(fz_town_data.keys(), fz_town_data.values())], '福州')
.set_series_opts(label_opts=opts.LabelOpts(is_show=True,
# return params.value[2]; // 不存在这个值,写个错误的让地图绘制默认值
formatter=JsCode("""
function(params){
if (typeof(params.data) == 'undefined') {
return params.value[2];
} else {
return params.data.name
+ params.data.value + '例';
}
}"""
))
)
.set_global_opts(
title_opts=opts.TitleOpts(
title='福州市新型冠状病毒疫情地图',
subtitle='其中,福州主城区(晋安、马尾、鼓楼、仓山、台江)\n共确诊{}例'.format(fz_town_data['福州市区'])),
visualmap_opts=opts.VisualMapOpts(is_show=True,
split_number=6,
is_piecewise=True, # 是否为分段型
pos_top='center',
pieces=[
{'min': 20},
{'min': 10, 'max': 19},
{'min': 5, 'max': 9},
{'min': 1, 'max': 4}]
)
)
)
return c
#%%
map_fz_disease_dis().render('福州疫情地图.html')
请参考本人其他篇绘制抓取实时数据,使用Basemap绘制分布图,使用plt绘制走势图的博文。
另外,pyecharts使用案例:
用Python pyecharts v1.x 绘制图形(一):柱状图、柱状堆叠图、条形图、直方图、帕累托图、饼图、圆环图、玫瑰图
用Python pyecharts v1.x 绘制图形(二):折线图、折线面积图、散点图、雷达图、箱线图、词云图