python爬取全国疫情数据视图化
问题描述:
python爬取全国疫情数据视图化接口转化,探讨解决办法,是什么问题影响的
答
试着爬取了一下网站,发现是返回的数据不全,可以把后面一些不完整的数据截取掉,然后再解析
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import time
import json
import requests
from datetime import datetime
url = 'https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_cn_day_counts&callback=&_=%d'%int(time.time()*1000)
s=requests.get(url=url).json()['data']
while s[-1]!='}':
s=s[:-1]
s+=']'
data = json.loads(s)
data.sort(key=lambda x:x['date'])
date_list = list() # 日期
confirm_list = list() # 确诊
suspect_list = list() # 疑似
dead_list = list() # 死亡
heal_list = list() # 治愈
for item in data:
month, day = item['date'].split('/')
date_list.append(datetime.strptime('2020-%s-%s'%(month, day), '%Y-%m-%d'))
confirm_list.append(int(item['confirm']))
suspect_list.append(int(item['suspect']))
dead_list.append(int(item['dead']))
heal_list.append(int(item['heal']))
答
这个最好将数据以表图展示,这样分析就比较清晰,画图用matplotlib比较好
答
从提供的信息看,是获取的字符串不符合json解析格式要求,json.loads时报错,先打印返回的内容看看,可尝试的解决办法:1.用字符串替换方法,将属性名是单引号的替换为双引号,使用eval或者ast.literal_eval转换,三是使用库demjson。
可参考:
https://www.jb51.net/article/117995.htm