如何使用不同的API

时间:2016-01-23 22:56:49

标签: python api wunderground

我试图通过使用天气API创建一个能够成功告诉你天气的程序。 这是我将使用的http://www.wunderground.com/weather/api/d/docs

我很难理解如何使用这个Api。我发现它相当令人困惑。我试图使用wunderground提供的示例代码,但它似乎并没有在我的编辑器中工作(可能是由于代码是python的另一个版本。)我使用的是python 3.5 任何评论和任何建议将非常感谢我如何使用这个api。

由于

1 个答案:

答案 0 :(得分:0)

以下是为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))