Last active
August 29, 2015 14:05
-
-
Save aaronlelevier/ee0ef0dfd91ce6a6414c to your computer and use it in GitHub Desktop.
Get the current weather for Las Vegas using Yahoo!'s Weather API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import xmltodict | |
def get_weather(url="http://weather.yahooapis.com/forecastrss?w=12795483&u=f"): | |
""" | |
Get the current weather for Las Vegas using Yahoo!'s Weather API | |
""" | |
try: | |
r = requests.get(url) | |
# parse bytes into a text string | |
text = r.content.decode("utf-8") | |
#convert xml text to OrderedDict | |
doc = xmltodict.parse(text) | |
# item contains all the main temp info | |
title = doc['rss']['channel']['title'] | |
condition = doc['rss']['channel']['item']['yweather:condition'] | |
weather = condition['@text'] | |
temp = condition['@temp'] | |
return "{0}. {1}. {2}°F.".format(title, weather, temp) | |
except requests.ConnectionError: | |
return "Sorry, the weather connection failed. Weather currently unavailable." | |
except KeyError: | |
return "Weather currently unavailable." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment