#!/usr/bin/python # weather.cgi. This python cgi script parses the page at the address below # for specific weather data and displays it in an html page. National # Weather Service data is free and unencumbered by license issues. # In most cases this script must be run from the cgi bin. Please check # your server configuration. This script is reasonably quick and could be # considerably quicker, but some speed has been sacrificed in an attempt # to make it more robust. A nice way to call it is as a server side # include with the following statement: # # Enjoy. http://www.braggtown.com # Set the url below to your location using http://weather.noaa.gov/index.html weather_url = "http://weather.noaa.gov/weather/current/KRDU.html" from urllib import urlopen import HTMLParser, string page = urlopen(weather_url).read() import HTMLParser class Stripper(HTMLParser.HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_fed_data(self): return ''.join(self.fed) stripper = Stripper() stripper.feed(page) stripped_text = stripper.get_fed_data() lines = stripped_text.split('\n') l = [] for line in lines: if line.strip(): l.append(line.strip()) i = 0 # To add data fields, first add a variable name to following list # then add a condition statement similar to those below for that variable # finally, make sure to create a print statement for it at the end wind = conditions = temp = humidity = False while i < len(l): if not wind: if l[i] == "Wind": wind = l[i +1] if not conditions: if l[i] == "Sky conditions": conditions =l[i+1] if not temp: if l[i] == "Temperature": temp = l[i+1] if not humidity: if l[i] == "Relative Humidity": humidity = l[i+1] i += 1 print "Content-Type: text/html\n" # The following statements control the presentation of the data. print "

" print "Current weather conditions in Raleigh
" print "Temperature: ", temp + "
" print "Conditions: ", conditions + "
" print "Wind: ", wind + "
" print "Relative humidity: ", humidity + "
" print "

"