Python天气API
我该如何将天气数据导入到Python程序中呢?
1 个回答
70
因为谷歌已经关闭了它的天气API,所以我建议你看看 OpenWeatherMap:
OpenWeatherMap提供免费的天气数据和天气预报API,适合用于各种地图服务,比如网页和手机应用。它的理念受到OpenStreetMap和维基百科的启发,旨在让信息对每个人都免费和可用。OpenWeatherMap提供了丰富的天气数据,比如当前天气地图、一周的天气预报、降水量、风速、云量、来自气象站的数据等等。天气数据来自全球的气象广播服务和超过40,000个气象站。
这不是一个Python库,但使用起来非常简单,因为你可以以JSON格式获取结果。
下面是一个使用 Requests 的例子:
>>> from pprint import pprint
>>> import requests
>>> r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London&APPID={APIKEY}')
>>> pprint(r.json())
{u'base': u'cmc stations',
u'clouds': {u'all': 68},
u'cod': 200,
u'coord': {u'lat': 51.50853, u'lon': -0.12574},
u'dt': 1383907026,
u'id': 2643743,
u'main': {u'grnd_level': 1007.77,
u'humidity': 97,
u'pressure': 1007.77,
u'sea_level': 1017.97,
u'temp': 282.241,
u'temp_max': 282.241,
u'temp_min': 282.241},
u'name': u'London',
u'sys': {u'country': u'GB', u'sunrise': 1383894458, u'sunset': 1383927657},
u'weather': [{u'description': u'broken clouds',
u'icon': u'04d',
u'id': 803,
u'main': u'Clouds'}],
u'wind': {u'deg': 158.5, u'speed': 2.36}}
这里是一个使用 PyOWM 的例子,它是一个封装了OpenWeatherMap网络API的Python库:
>>> import pyowm
>>> owm = pyowm.OWM()
>>> observation = owm.weather_at_place('London,uk')
>>> w = observation.get_weather()
>>> w.get_wind()
{u'speed': 3.1, u'deg': 220}
>>> w.get_humidity()
76
官方的API文档可以在 这里 找到。
要获取API密钥,可以在OpenWeatherMap上注册,链接在 这里。