Python爬取腾讯疫情实时数据并存储到mysql数据库
发布时间:2021-05-20 14:17:23 所属栏目:大数据 来源: https://www.cnblogs.com/rainb
导读:? ? ? ? ? ?思路: 在腾讯疫情数据网站F12解析网站结构,使用Python爬取当日疫情数据和历史疫情数据,分别存储到details和history两个MysqL表。 ? ①此方法用于爬取每日详细疫情数据 1 import requests 2 json 3 time 4 def get_details(): 5 url = ' https:
? ? ? ? ? ?思路: 在腾讯疫情数据网站F12解析网站结构,使用Python爬取当日疫情数据和历史疫情数据,分别存储到details和history两个MysqL表。 ? ①此方法用于爬取每日详细疫情数据 1 import requests 2 json 3 time 4 def get_details(): 5 url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=jQuery34102848205531413024_1584924641755&_=1584924641756' 6 headers ={ 7 user-agent': Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400 8 } 9 res = requests.get(url,headers=headers) 10 #输出全部信息 11 print(res.text) 12 response_data = json.loads(res.text.replace(jQuery34102848205531413024_1584924641755(','')[:-1]) 13 输出这个字典的键值 dict_keys(['ret','data'])ret是响应值,0代表请求成功,data里是我们需要的数据 14 print(response_data.keys()) 15 """上面已经转化过一次字典,然后获取里面的data,因为data是字符串,所以需要再次转化字典 16 print(json.loads(reponse_data['data']).keys()) 17 结果: 18 dict_keys(['lastUpdateTime','chinaTotal','chinaAdd','isShowAdd','showAddSwitch',19 'areaTree','chinaDayList','chinaDayAddList','dailyNewAddHistory','dailyHistory',1)">20 'wuhanDayList','articleList']) 21 lastUpdateTime是最新更新时间,chinaTotal是全国疫情总数,chinaAdd是全国新增数据, 22 isShowAdd代表是否展示新增数据,showAddSwitch是显示哪些数据,areaTree中有全国疫情数据 23 """ 24 areaTree_data = json.loads(response_data[data'])[areaTree'] 25 temp=json.loads(response_data[26 print(temp.keys()) 27 print(areaTree_data[0].keys()) 28 29 获取上一级字典里的areaTree 30 然后查看里面中国键值 31 print(areaTree_data[0].keys()) 32 dict_keys(['name','today','total','children']) 33 name代表国家名称,today代表今日数据,total代表总数,children里有全国各地数据,我们需要获取全国各地数据,查看children数据 34 print(areaTree_data[0]['children']) 35 这里面是 36 name是地区名称,today是今日数据,total是总数,children是市级数据, 37 我们通过这个接口可以获取每个地区的总数据。我们遍历这个列表,取出name,这个是省级的数据,还需要获取市级数据, 38 需要取出name,children(市级数据)下的name、total(历史总数)下的confirm、heal、dead,today(今日数据)下的confirm(增加数), 39 这些就是我们需要的数据 40 41 print(areaTree_data[0]['children']) 42 for province_data in areaTree_data[0]['children']: 43 print(province_data) 44 45 ds= temp[lastUpdateTime46 details=[] 47 for pro_infos in areaTree_data[0][children]: 48 province_name = pro_infos[name'] 省名 49 for city_infos in pro_infos[50 city_name = city_infos[ 市名 51 confirm = city_infos[total'][confirm']历史总数 52 confirm_add = city_infos[today今日增加数 53 heal = city_infos[heal治愈 54 dead = city_infos[dead死亡 55 print(ds,province_name,city_name,confirm,confirm_add,heal,dead) 56 details.append([ds,dead]) 57 return details 单独测试方法: 1 d=get_details() 2 print(d) ? ②此方法用于爬取历史详细数据 get_history(): https://view.inews.qq.com/g2/getOnsInfo?name=disease_other&callback=jQuery341026745307075030955_1584946267054&_=1584946267055 7 } 10 print(res.text) 11 response_data = json.loads(res.text.replace(jQuery341026745307075030955_1584946267054(12 print(response_data) 13 data = json.loads(response_data[ print(data.keys()) 15 chinaDayList = data[chinaDayList历史记录 16 chinaDayAddList = data[chinaDayAddList历史新增记录 17 history = {} 18 for i in chinaDayList: 19 ds = 2021.' + i[date时间 20 tup = time.strptime(ds,1)">%Y.%m.%d) 21 ds = time.strftime(%Y-%m-%d改变时间格式,插入数据库 22 confirm = i[23 suspect = i[suspect24 heal = i[25 dead = i[26 history[ds] = {':confirm,1)">':suspect,1)">':heal,1)">:dead} 27 chinaDayAddList: 28 ds = 29 tup = time.strptime(ds,1)">30 ds = time.strftime(31 confirm_add = i[32 suspect_add = i[33 heal_add = i[34 dead_add = i[35 history[ds].update({confirm_add':confirm_add,1)">suspect_add':suspect_add,1)">heal_add':heal_add,1)">dead_add:dead_add}) 36 return history 单独测试此方法: h=get_history() print(h) ? ③此方法用于数据库的连接与关闭: pyMysqL traceback get_conn(): 5 6 :return: 连接,游标 7 8 创建连接 9 conn = pyMysqL.connect(host="127.0.0.1",1)">10 user=root11 password=00042912 db=mydb13 charset=utf814 创建游标 15 cursor = conn.cursor() 执行完毕返回的结果集默认以元组显示 16 return conn,cursor 17 close_conn(conn,cursor): if cursor: 19 cursor.close() 20 conn: 21 conn.close() ? ④此方法用于更新并插入每日详细数据到数据库表: update_details(): 2 3 更新 details 表 4 :return: 6 cursor = None 7 conn =try: 9 li = get_details() 10 conn,cursor = get_conn() 11 sql = insert into details(update_time,province,city,dead) values(%s,%s,%s)" 12 sql_query = select %s=(select update_time from details order by id desc limit 1)' 对比当前最大时间戳 13 cursor.execute(sql_query,li[0][0]) 14 if not cursor.fetchone()[0]: 15 print(f{time.asctime()}开始更新最新数据16 for item li: cursor.execute(sql,item) 18 conn.commit() 提交事务 update delete insert操作 19 {time.asctime()}更新最新数据完毕20 else21 {time.asctime()}已是最新数据!22 except23 traceback.print_exc() 24 finally25 close_conn(conn,cursor) 单独测试能否插入数据到details表: 1 update_details()
? ? ? ⑤此方法用于插入历史数据到history表 insert_history(): 插入历史数据 9 dic = get_history() {time.asctime()}开始插入历史数据11 conn,1)">12 sql = insert into history values(%s,1)">13 for k,v dic.items(): 14 item 格式 {'2021-01-13': {'confirm': 41,'suspect': 0,'heal': 0,'dead': 1} 15 cursor.execute(sql,[k,v.get("),1)">),1)">16 v.get(17 v.get()]) 18 19 conn.commit() {time.asctime()}插入历史数据完毕21 22 23 24 close_conn(conn,1)">单独测试能否插入数据到history表: |