天气预报查询系统
#天气预报
#引入requests
import requests
#引入python内置的包json,用来解析和生成
import json
#url统一资源定位符 主机域名/目录/?地点&格式。。。
#windows+r cmd 打开命令行工具 输入pip install requests
print('欢迎进入天气预报查询系统!')
while 1:
city = input('请输入想要查询的城市的名称(输入0退出):')
if city == '0':
print('已退出天气预报查询系统!')
break
else:
url = 'http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'%city
#使用requests发起请求,接受返回的结果
response = requests.get(url)
#使用loads函数 将json字符串转化为python 的字典或列表
rs_dict = json.loads(response.text)
#取出error
error_code = rs_dict['error']
if error_code == 0:
#从字典中取出数据
results = rs_dict['results']
#根据索引取出城市天气信息字典
info_dict = results[0]
#取出城市名称
city_name = info_dict['currentCity']
pm25 = info_dict['pm25']
print('当前城市:%s pm25:%s'%(city_name,pm25))
#取出天气列表
weather_data = info_dict['weather_data']
#for循环取出每一天的小字典
for weather_dict in weather_data:
date = weather_dict['date']
weather = weather_dict['weather']
wind = weather_dict['wind']
temperature = weather_dict['temperature']
print('%s %s %s %s'%(date,weather,wind,temperature))
index = info_dict['index']
for index_dict in index:
title = index_dict['title']
zs = index_dict['zs']
tipt = index_dict['tipt']
des = index_dict['des']
print('%s %s %s %s'%(title,zs,tipt,des))
else:
print('没有查询到天气信息')