Python 天气 API

40

我该如何将天气数据导入 Python 程序?

1个回答

70

由于谷歌已关闭其天气API,我建议尝试查看OpenWeatherMap

OpenWeatherMap服务提供免费的天气数据和预报API,适用于任何地图服务,如Web和智能手机应用程序。该服务的理念受到了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 Web 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密钥,请在此处注册open weather map here


5
OpenWeatherMap Web API的资源根据不同的端点使用不同的JSON格式,因此解析起来非常棘手... 避免所有这些麻烦并且不要重复造轮子,可以使用外部库,例如:PyOWM https://github.com/csparpa/pyowm - csparpa
1
@csparpa 谢谢,我已经更新了答案! - Paolo Moretti
有趣。我如何从 {u'speed': 3.1, u'deg': 220} 中打印速度?@paolo - Yoweli Kachala
1
@user2763992,风速在由get_wind返回的字典中。尝试 print w.get_wind()['speed'] - Paolo Moretti
API限制请求方面怎么样?每天可以完成多少个请求? - enneppi
你好 - 你知道是否可以“循环”这段代码,以便始终获取最新的天气信息吗? - Sjharrison

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接