Python编程-使用爬虫程序爬取肺炎疫情数据-1 爬取给定国家的历史疫情信息

Alice ·
更新时间:2024-09-21
· 632 次阅读

首先,我们进入目标页面:腾讯网

如下图所示,按F12进入开发者选项,接着点击 【网络】(如下箭头所示),然后刷新页面。

刷新页面之后,我们就可以看到下面多了很多内容,这是浏览器接收到服务器返回的信息。

点击选中的任意一行,我们可以看到:

(上面截图使用浏览器:火狐浏览器)

(上面截图使用浏览器:谷歌浏览器)

通过上图,我们可以看到服务器返回的部分国家的历史疫情信息,客户端请求方法为POST。

现在,我们开始准备爬取数据,如下图所示,复制url:

意大利: https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?country=%E6%84%8F%E5%A4%A7%E5%88%A9& 伊朗: https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?country=%E4%BC%8A%E6%9C%97& 西班牙: https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?country=%E8%A5%BF%E7%8F%AD%E7%89%99&

其中,URL链接后面的country=之后是国家名(编码方式问题,不宜阅读)

由此,我们可以得到想要的URL接口:

https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?country=国家名

下面是全部代码,爬取结果保存至excel文件中:

''' 爬取给定国家的疫情历史信息 ''' import requests import xlwt import datetime import json import sys def getURLContent(url): headers = { 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36' } response = requests.post(url, headers=headers) return response.status_code, response def getCountryEpidemiSituationInfo(workbook, country_list): for index, country_i in enumerate(country_list): # 创建一个worksheet worksheet = workbook.add_sheet(country_i) print("开始爬取 %s 的疫情数据... ... " % country_i) url = 'https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?country=%s' % country_i status_code, data = getURLContent(url) if status_code != 200: print("%s数据爬取失败,状态码%d" % (country_i, status_code)) sys.exit() data = data.json()["data"] if data == None: print("%s数据爬取数据为空" % country_i) break worksheet.col(0).width = 128 * 20 # 设置excel中第A列的宽度(方便日期数据展示) current_row_index = 0 # 记录当前所写入数据的行号 # 将列标题写入excel for i, str_col in enumerate(['date', 'confirm_add', 'confirm', 'heal', 'dead', 'suspect']): worksheet.write(current_row_index, i, str_col) # 参数对应 行, 列, 值 current_row_index += 1 # 往excel中写入日期格式 style = xlwt.XFStyle() style.num_format_str = 'YYYY/MM/DD' # 将抓取到的疫情数据写入excel for data_i in data: worksheet.write(current_row_index, 0, datetime.datetime.strptime('2020.' + data_i['date'], "%Y.%m.%d"), style) worksheet.write(current_row_index, 1, data_i['confirm_add']) worksheet.write(current_row_index, 2, data_i['confirm']) worksheet.write(current_row_index, 3, data_i['heal']) worksheet.write(current_row_index, 4, data_i['dead']) worksheet.write(current_row_index, 5, data_i['suspect']) current_row_index += 1 if __name__ == "__main__": # 创建一个workbook 设置编码 workbook = xlwt.Workbook(encoding='utf-8') # 添加要爬取疫情数据的国家 country = ["美国", "加拿大", "意大利", "英国", "法国", "丹麦", "韩国", "日本本土", "德国"] getCountryEpidemiSituationInfo(workbook, country) # 保存 workbook.save('./data/疫情历史数据.xls') #这里不要使用.xlsx格式保存,否则无法打开!!!原因与库xlwt有关,如需要保存为.xlsx格式,需要使用其他第三方库操作

结果:


作者:桐小哥



爬虫 肺炎 疫情 程序 数据 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号