# Jay Summet # CS 1803 Example Program # Copyright 2010 # #This program demonstrates downloading an XML file and #immediately parsing it using the ElementTree xml module. # #We extract several pieces of weather information and then write them #to a webpage. import xml.etree.ElementTree as etree #for XML parsing import urllib.request #For URL Downloading #This function will return a tuple of weather data for a particular #NOAA weather station, as specified by the four leter station code given #as a string. (e.g. Atlanta's Airport is "KFTY") # The tuple of data contains the following items: # 0 - Location # 1 - Temperature (c & f) # 2 - Relative Humidity # 3 - URL to web icon # 4 - URL to two day history def getWeather(stationCode): url = "http://www.weather.gov/data/current_obs/" + stationCode +".xml" response = urllib.request.urlopen(url) tree = etree.parse(response) root = tree.getroot() locationString = None tempString = None relativeHumidity = None iconURL = None twoDayURL = None locItem = root.find("location") locationString = locItem.text tempItem = root.find("temperature_string") tempString = tempItem.text rhItem = root.find("relative_humidity") relativeHumidity = rhItem.text ibItem = root.find("icon_url_base") icItem = root.find("icon_url_name") iconURL = ibItem.text + icItem.text tdItem = root.find("two_day_history_url") twoDayURL = tdItem.text return( (locationString, tempString, relativeHumidity, iconURL, twoDayURL) ) #This function will create a website that lists the weather #at various locations. You give it the list of location codes #and an output filename. It will call the getWeather function #for each location, and export the data in an HTML table. def createWebsite(weatherLocations, filename): #Open the file for writing, and write out the static #top of the webpage. fOut = open(filename, "w") fOut.write( """ Custom Weather Report

Your Custom Weather Report

""" ) #Write one row of data for each location for location in weatherLocations: weather = getWeather(location) fOut.write("") fOut.write('' ) fOut.write("") fOut.write("") fOut.write("") fOut.write("\n\n") #After we write out the table of data, end the webpage... fOut.write("
Icon (click for history) Location Temperature Relative Humidity
" + weather[0] + "" + weather[1] + "" + weather[2] + "
") createWebsite( [ "KFTY", "KSEA", "KSFO", "KMCO", "KJFK", "KYKM",], "weatherWeb.html") print("file written...")