import requests
#获取城市以及对应的adcode
def get_city():
#确定url
base_url = 'https://www.amap.com/service/cityList?'
# 发送请求
response = requests.get(base_url,headers=headers)
# print(response.text)
#解析json数据
json_data = response.json()
# print(json_data) 得到的json数据放到在线json解析网站中,方便分析结构
#获取adcode
#热门城市
city_adcode = []
for data in json_data['data']['cityData']['hotCitys']:
city_adcode.append((data['adcode'],data['name'],data['x'],data['y']))
#其他城市
#for data in json_data['data']['cityData']['otherCitys']:
#city_adcode.append((data['adcode'],data['name']))
return city_adcode
print(city_adcode)
def get_weather(adcode,city_name,X,Y):
'''
获取城市天气
Query String Parameters
adcode:500000
'''
#基础url
base_url = 'https://www.amap.com/service/weather?adcode={}'.format(adcode)
response = requests.get(base_url, headers=headers) #发送请求,获取响应
json_data = response.json() #获取json数据
#通过得到的json数据,在在线解析网站中解析后,分析其结构,找到要获取的在哪一个字典或者列表列表
#分层的取出来即可
if json_data['data']['result']=='true':
weather = json_data['data']['data'][0]['forecast_data'][0]['weather_name'] #当前天气
#最大温度
max_temp = json_data['data']['data'][0]['forecast_data'][0]['max_temp']
#最小温度
min_temp = json_data['data']['data'][0]['forecast_data'][0]['min_temp']
t_weather = json_data['data']['data'][1]['forecast_data'][0]['weather_name'] #明天天气
#最大温度
t_max_temp = json_data['data']['data'][1]['forecast_data'][0]['max_temp']
#最小温度
t_min_temp = json_data['data']['data'][1]['forecast_data'][0]['min_temp']
# print(weather, max_temp, min_temp)
dic = {}
dic['城市'] = city_name
dic['adcode'] = adcode
dic['X'] = X
dic['Y'] = Y
dic['天气'] = weather
dic['温度'] = '{}/{}℃'.format(min_temp,max_temp)
dic['明日天气'] = t_weather
dic['明日温度'] = '{}/{}℃'.format(t_min_temp,t_max_temp)
print(dic)
def main():
city_adcode = get_city()
# print(city_adcode)
#将每个城市的adcode传给get_weather
#city_adcode有城市和adcode
for i in city_adcode:
adcode = i[0]
city_name = i[1]
X = i[2]
Y = i[3]
get_weather(adcode,city_name,X,Y)
if __name__ == '__main__':
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537',
'X-Requested-With': 'XMLHttpRequest',
}
main()
大佬 能在我这个代码上面把城市改成省会城市吗 |