'''
3、获取高德的所有城市天气信息
北京接口: https://www.amap.com/service/weather?adcode=110000
城市adcode列表:https://www.amap.com/service/cityList?version=201951410
获取到天气情况,打印出来
{
"adcode":"110000",
"name":"北京",
“weather”"晴"
},
'''
'''
1.先查询城市adcode
2.再城市adcode对应的天气查询
3.拼接
二合一查找
'''
import requests,os,json
base_url = 'https://www.amap.com/service/cityList?version=201951410'
params = {
'version': '20195141'
}
# str_data = requests.get(base_url,params=params).text
json_data_list = json.loads(requests.get(base_url,params=params).text)
#获取cityByLetter
#获取城市字典:A-Z开头的
city_list_FirstBig = json_data_list.get('data').get('cityByLetter')
print(city_list_FirstBig.keys())
#城市首字母keys_genter
data_list = [i for i in city_list_FirstBig.keys()]#城市首字母keys_genter
print(data_list)
# print(type(data_list))
#细化每个城市
a_big_list=[]
for FirstBig_cities in data_list:
#获取每个城市的列表
# print(city_list_FirstBig.get(FirstBig_cities))
for cities_dict in city_list_FirstBig.get(FirstBig_cities):
hahaha = {}
hahaha['adcode'] = cities_dict.get('adcode')#获取每个城市的adcode,根据获取到的adcode 查询天气
hahaha['name']= str(cities_dict.get('name'))
#根据获取到的adcode再次请求数据,组织数据结构保存到列表中
weather_base_url = 'https://www.amap.com/service/weather?'
adcode_params = {
'adcode': int(hahaha.get('adcode')),
}
# print(adcode_params)
adcodes_response = json.loads(str(requests.get(weather_base_url, params=adcode_params).text)) # 获取天气
adcodes_response_data = adcodes_response.get('data')
adcodes_response_data_data = adcodes_response_data.get('data')
try:
city_weather = adcodes_response_data_data[1].get('forecast_data')
hahaha['weather'] = str(city_weather[0].get('weather_name'))
except TypeError as a:
print(a)
finally:
a_big_list.append(hahaha)
print(hahaha)
for i in a_big_list:
print(i)
print()
#获取adcode对应的天气
weather_base_url = 'https://www.amap.com/service/weather?'
adcode_params={
'adcode': '110000',
}
adcodes_response = json.loads(str(requests.get(weather_base_url,params=adcode_params).text))#获取天气
adcodes_response_data = adcodes_response.get('data')
adcodes_response_data_data = adcodes_response_data.get('data')
weather = adcodes_response_data_data[1].get('forecast_data')
weather = weather[0].get('weather_name')
print(weather)