Friday, July 13, 2012

Python Script to fetch the current weather information


Here is a python script that will get the current weather information of any place. This script makes use of Google API.

How to run the script
python script_name   place_name/postal_code

Example:
Download the code and save it in get_weather.py file
Now to get the present weather information of London, execute the following command
python get_weather.py london

To get the weather information of Bonn, whose pin code is 53175, execute the following
python get_weather.py 53175

Following is the code:

import sys
import urllib2
from xml.dom.minidom import parse, parseString
from time import gmtime, strftime

url = "http://www.google.com/ig/api?weather="
url = url+sys.argv[1]

u = urllib2.urlopen(url)
filename="weather_report_"+sys.argv[1]+".xml"
localFile = open(filename, 'w')
localFile.write(u.read())
localFile.close()

#Parse the XML file to extract important information
doc=parse(filename)

# location info
fi = doc.getElementsByTagName("forecast_information")[0]

city = fi.childNodes[0]
print "City: " + city.attributes["data"].value

pc = fi.childNodes[1]
print "Postal Code: " + pc.attributes["data"].value

#weather info
cc=doc.getElementsByTagName("current_conditions")[0]

cond = cc.childNodes[0]
print "Type: " + cond.attributes["data"].value

temp_f=cc.childNodes[1]
temp_c=cc.childNodes[2]
print "Temperature: " + temp_f.attributes["data"].value + " F / " +temp_c.attributes["data"].value + " C"

humidity = cc.childNodes[3]
print humidity.attributes["data"].value

wc = cc.childNodes[5]
print wc.attributes["data"].value