码迷,mamicode.com
首页 > 编程语言 > 详细

Python获取实况天气及7天预报

时间:2015-12-22 21:17:13      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:

国内众多天气APP以及网站提供的天气实况和预报信息,最终的来源都是官方气象局。当然也有一些软件和网站数据来源是国外的气象机构。

那么我们也可以自己来获取,中国天气网提供了免费的数据接口,不过我这里使用的是由 和风天气 所提供的接口,获取数据的原始格式是 Json ,可以很容易的作为Python的字典类型使用。

数据的内容包括城市信息,天气实况(半小时左右更新一次),空气质量,以及7天详细预报。

需要一个百度的APIKEY,要注册一下就可以获取。在 http://apistore.baidu.com/apiworks/servicedetail/478.html 页面点击“获取apikey”

 1 #!/usr/bin/env python3
 2 import json
 3 import urllib.request
 4 
 5 
 6 def getCityWeather(cityName, bdAPI):
 7     ‘‘‘
 8     cityName:‘xian‘, bdAPI:百度apikey
 9     ‘‘‘
10     url = ‘http://apis.baidu.com/heweather/weather/free?city=‘ + cityName   # https也可以
11     request = urllib.request.Request(url)
12     request.add_header(‘apikey‘, bdAPI)
13     response = urllib.request.urlopen(request)
14     weatherInfo = response.read().decode(‘utf-8‘)
15     jsonDatas = json.loads(weatherInfo)
16     for k in jsonDatas.keys():  # 实际上只有一个键值对
17         dictDatas = jsonDatas[k][0]
18     return dictDatas
19 
20 
21 if __name__ == ‘__main__‘:
22     dictDatas = getCityWeather(‘xian‘, ‘xxxxxxxxxxxxxxxxxxxxxxxxxxx‘) # 替换city和apikey
23     print(dictDatas[‘basic‘][‘city‘])  # 地名
24     print(‘更新时间:‘, dictDatas[‘basic‘][‘update‘][‘loc‘])  # 更新时间
25     print(‘实况:‘, dictDatas[‘now‘])  # 实况数据
26     if ‘aqi‘ in dictDatas:  # 有些地方没有AQI数据,比如县级区域
27         print(‘AQI:‘, dictDatas[‘aqi‘][‘city‘])

 

执行结果:

西安
更新时间: 2015-12-22 20:05
实况: {‘tmp‘: ‘5‘, ‘pcpn‘: ‘0‘, ‘hum‘: ‘53‘, ‘fl‘: ‘2‘, ‘wind‘: {‘dir‘: ‘东风‘, ‘spd‘: ‘19‘, ‘sc‘: ‘4-5‘, ‘deg‘: ‘10‘}, ‘cond‘: {‘code‘: ‘502‘, ‘txt‘: ‘霾‘}, ‘pres‘: ‘1024‘, ‘vis‘: ‘1‘}
AQI: {‘qlty‘: ‘重度污染‘, ‘pm25‘: ‘194‘, ‘o3‘: ‘15‘, ‘so2‘: ‘78‘, ‘co‘: ‘3‘, ‘aqi‘: ‘245‘, ‘no2‘: ‘96‘, ‘pm10‘: ‘328‘}

 

Python获取实况天气及7天预报

标签:

原文地址:http://www.cnblogs.com/aeropig/p/weather_api.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!