import requests
from pandas import DataFrame
url = "http://apis.juhe.cn/springTravel/risk?key=d35f34536565d5cfd9289e2c7e7b27db"
# 接入外部API获取疫情风险区域
data = requests.get(url).json()
# 所有高风险地区列表
list_high = []
# 所有中风险地区列表
list_middle = []
# 所有低风险地区列表
list_low = []
for item in data["result"]["high_list"]:
# 高风险地区字典
dict_higt = {
"type": item["type"], # 类型1.为全部区域2.为部分区域
"province": item["province"], # 省份
"city": item["city"], # 城市
"county": item["county"], # 地区
"area_name": item["area_name"], # 疫情区域
"communitys": item["communitys"] # 疫情详细地点
}
# 中风险地区字典
dict_middle = {
"type": item["type"],
"province": item["province"],
"city": item["city"],
"county": item["county"],
"area_name": item["area_name"],
"communitys": item["communitys"]
}
# 低风险地区字典
dict_low = {
"type": item["type"],
"province": item["province"],
"city": item["city"],
"county": item["county"],
"area_name": item["area_name"],
"communitys": item["communitys"]
}
# 将字典添加进列表
list_high.append(dict_higt)
list_middle.append(dict_middle)
list_low.append(dict_low)
# 越秀区高风险列表
list_yue_xiu = []
# 天河区高风险列表
list_tian_he = []
for item in list_high:
if item["area_name"] not in ["广东省 广州市 越秀区", "广东省 广州市 天河区"]:
continue
# 将天河区和越秀区的详细高风险区域放入列表
if item["area_name"] == "广东省 广州市 越秀区":
list_yue_xiu += item["communitys"]
else:
list_tian_he += item["communitys"]
# 放置记录天河区和越秀区风险区域字典的列表
list_high_rick = []
len_yue_xiu = len(list_yue_xiu)
len_tian_he = len(list_tian_he)
# 三目运算得到两列表的最大长度
max_len = len_yue_xiu if len_yue_xiu >= len_tian_he else len_tian_he
for i in range(max_len):
dict_higt_risk = {
# 索引小于自身长度,获取元素,反之为空
"越秀区": list_yue_xiu[i] if i < len_yue_xiu else "",
"天河区": list_tian_he[i] if i < len_tian_he else ""
}
# 添加字典进列表
list_high_rick.append(dict_higt_risk)
# 转换为表格
DataFrame(list_high_rick).to_excel("xxx.xlsx", index=False)