Python 中json的应用实例----天气预报
2018-01-25 19:17
567 查看
# 天气预报 # 引入requests import requests # 引入python中内置的包json,用来解析和生成json数据 import json city = input('请输入要查询的城市名称:') # url 统一资源定位符 # cmd 打开命令行工具 输入 pip install requests url = 'http://api.map.baidu.com/telematics/v3/weather?location= %s &output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'%city # 使用requests发起请求,接受返回的结果 rs = requests.get(url) #rs:<Response [200]> # 使用loads函数,将json字符串转换为python的字典或列表 rs_dict = json.loads(rs.text) # 取出error error_code = rs_dict['error'] # 如果取出的error为0,表示数据正常,否则没有查询到结果 if error_code == 0: # 从字典中取出数据 results = rs_dict['results'] # 根据索引取出城市天气信息字典 info_dict = results[0] # 根据字典的key,取出城市名称 city_name = info_dict['currentCity'] # 取出pm值 pm25 = info_dict['pm25'] print ('当前城市: %s pm值: %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)) else: print ('没有查询到天气信息')
相关文章推荐
- Android应用实例之----天气预报程序
- Android应用实例之----天气预报程序
- 【Android应用开发】-(17)获取Google天气预报通过Xml和JSON解析数据
- python用json解析爬取天气预报数据
- Http请求和Json解析结合实例 (简易的天气预报系统)
- Android应用实例之----天气预报程序.
- Python爬虫天气预报实例详解(小白入门)
- Android应用实例之----天气预报程序.
- Android应用实例之----天气预报程序.
- 类的应用1---景点、快递、内涵段子、天气预报(json数据的爬取)
- Android应用实例之----天气预报程序
- 基于python的天气预报(json)
- python中zip()方法应用实例分析
- Json解析之天气预报
- python对json的操作及实例解析
- python的re模块应用实例
- 国家气象局免费天气预报接口,城市代码(JSON格式)
- python实例3-天气小模块
- python爬虫"Hello World"级入门实例(二),使用json从中国天气网抓取数据
- 国家气象局提供的天气预报接口(完整Json接口)