如何使用不同的 API



我正在尝试创建一个程序,该程序可以通过使用天气API成功告诉您天气。这是我将使用的 API http://www.wunderground.com/weather/api/d/docs

我正在努力了解如何使用此 API。我发现它相当令人困惑。我尝试使用wunder提供的示例代码,但是它似乎在我的编辑器中不起作用(可能是由于代码是python的另一个版本。我正在使用python 3.5关于如何使用此 API 的任何评论和任何建议将不胜感激。

谢谢

下面是为 Python 3 修改的示例代码:

from urllib.request import Request, urlopen
import json
API_KEY = 'your API key'
url = 'http://api.wunderground.com/api/{}/geolookup/conditions/q/IA/Cedar_Rapids.json'.format(API_KEY)
request = Request(url)
response = urlopen(request)
json_string = response.read().decode('utf8')
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print("Current temperature in %s is: %s" % (location, temp_f))
response.close()

显然,您需要注册并获得API密钥。使用该键作为 API_KEY 的值。如果您在登录时查看代码示例,则密钥将已插入到您的 URL 中。

你也可以使用requests模块,它更容易使用,并支持Python 2和3:

import requests
API_KEY = 'your API key'
url = 'http://api.wunderground.com/api/{}/geolookup/conditions/q/IA/Cedar_Rapids.json'.format(API_KEY)
response = requests.get(url)
parsed_json = response.json()
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print("Current temperature in %s is: %s" % (location, temp_f))

最新更新