Here is the sample code modified for 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()
Obviously you need to sign up and get an API key. Use that key as the value for API_KEY
. If you look at the code sample whilst logged in the key will already be inserted into the URL for you.
You could also use the requests
module which is easier to work with, and supports Python 2 and 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))