Python天气API

2024-04-20 07:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 数据程序天气
1条回答
网友
1楼 · 发布于 2024-04-20 07:20:49

既然Google已经关闭了它的天气API,我建议查看一下OpenWeatherMap

The OpenWeatherMap service provides free weather data and forecast API suitable for any cartographic services like web and smartphones applications. Ideology is inspired by OpenStreetMap and Wikipedia that make information free and available for everybody. OpenWeatherMap provides wide range of weather data such as map with current weather, week forecast, precipitation, wind, clouds, data from weather Stations and many others. Weather data is received from global Meteorological broadcast services and more than 40 000 weather stations.

它不是一个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文档是here提供的。

要获得API密钥,请注册以打开天气图here

相关问题 更多 >