Python Weather API

Ste*_*ven 31 python api weather temperature

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

Pao*_*tti 52

由于Google已关闭其天气API,我建议您查看OpenWeatherMap:

OpenWeatherMap服务提供适用于任何制图服务(如网络和智能手机应用程序)的免费天气数据和预测API.意识形态的灵感来自OpenStreetMap和Wikipedia,它们使信息免费并且可供所有人使用.OpenWeatherMap提供广泛的天气数据,例如当前天气地图,周预报,降水,风,云,气象站的数据等等.天气数据来自全球气象广播服务和40 000多个气象站.

它不是一个Python库,但它非常易于使用,因为您可以获得JSON格式的结果.

以下是使用请求的示例:

>>> 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}}
Run Code Online (Sandbox Code Playgroud)

以下是使用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
Run Code Online (Sandbox Code Playgroud)

官方API文档可在此处获得.

要获取API密钥注册,请在此处打开天气图

  • OpenWeatherMap Web API资源使用不同的JSON blob格式化,具体取决于端点.因此,解析是非常糟糕的...避免所有这些麻烦,不要通过使用外部库重新发明轮子 - 例如:PyOWM https://github.com/csparpa/pyowm (3认同)