Musings of a computer science student
Code snippet: Get a weather condition using Python and Google Weather API
Here’s a simple Python code snippet for finding the weather condition of any given city using Google’s Weather API. It’s also published on GitHub if you want to clone it.
import urllib2
def getWeather(city):
#create google weather api url
url = "http://www.google.com/ig/api?weather=" + urllib2.quote(city)
try:
# open google weather api url
f = urllib2.urlopen(url)
except:
# if there was an error opening the url, return
return "Error opening url"
# read contents to a string
s = f.read()
# extract weather condition data from xml string
weather = s.split("<current_conditions><condition data=\"")[-1].split("\"")[0]
# if there was an error getting the condition, the city is invalid
if weather == "<?xml version=":
return "Invalid city"
#return the weather condition
return weather
def main():
while True:
city = raw_input("Give me a city: ")
weather = getWeather(city)
print(weather)
if __name__ == "__main__":
main()
Update: GitHub is awesome because it allows very easy forking. Beau Martínez has made a fork of my script that includes Python 3 support, XML parsing instead of RegEx searching, and temperature reporting.
| Print article | This entry was posted by Juliana Peña on February 19, 2010 at 11:09 am, and is filed under Code snippet. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |


about 6 months ago
Uff, eso serviria para una pieza con bacterias que huelen a tierra mojada
about 6 months ago
D: Cómo supiste?
about 5 months ago
you are awesome , thank you for every topic you posted in your blog , you are really geek and really helpful
i am now proudly following you on twitter
greeting from Egypt
about 2 months ago
You are awesome I wanna be a programmer like you
about 2 months ago
You are awesome I wanna be a programmer like you
about 2 months ago
You are awesome I wanna be a programmer like you