看看关于解析json的问题
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 = []
zd=json_data["data"]["cityData"]["provinces"]
for x in zd:
if len(zd["cities"])>0 :
city_adcode.append((zd["adcode"],zd["cities"]["name"],zd["x"],zd["y"]))
else:
city_adcode.append((zd["adcode"],zd["name"],zd["x"],zd["y"]))
return city_adcode
def get_weather(adcode,city_name,X,Y):
'''
获取城市天气
'''
#基础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']['forecast_data']['weather_name']#当前天气
#最大温度
max_temp = json_data['data']['data']['forecast_data']['max_temp']
#最小温度
min_temp = json_data['data']['data']['forecast_data']['min_temp']
t_weather = json_data['data']['data']['forecast_data']['weather_name']#明天天气
#最大温度
t_max_temp = json_data['data']['data']['forecast_data']['max_temp']
#最小温度
t_min_temp = json_data['data']['data']['forecast_data']['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
city_name = i
X = i
Y = i
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()
看一下我那个提取城市那块为什么只有直辖市
还有就是最下面想x【1】 y【2】那些是什么意思 有人不{:5_92:} 另外的贴子回复过你了:
i的值是这种:('110000', '北京', '116.405285', '39.904989')
i是:110000
i是:北京
其他以此类推,就是普通用index访问元组的元素,没什么特别知识点。
页:
[1]