#!/usr/bin/env python # # get_weather.py - v0.1 # # Copyright (c) 2008 - Rich Burridge - Sun Microsystems Inc. # All Rights Reserved. # # Uses BeautifulSoup.py from http://www.crummy.com/software/BeautifulSoup/ # # Usage: # # $ python ./get_weather.py # # Script to get the 10 day weather forecast for the given zip code by # using BeautifulSoup to scrape the weather.com web page, then send email. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. import smtplib import sys import urllib2 from BeautifulSoup import BeautifulSoup # -------- START OF USER CONFIGURATION SECTION -------- # Zip code to get 10 day forecast for. # zipCode = "94024" # Email address to sent results to. # emailAddr = "someone@somewhere.com" # -------- END OF USER CONFIGURATION SECTION -------- # Base URL the weather.com weather forecast. # url = "http://www.weather.com/weather/tenday/" + zipCode + \ "?from=36hr_fcst10DayLink_undeclared" # Email message template. # messageTemplate = """\ From: %s To: %s Subject: %s %s """ def sendEmail(results): SERVER = "localhost" FROM = emailAddr TO = [ emailAddr ] SUBJECT = "10 day Forecast For Zip: %s." % zipCode TEXT = "" for result in results: TEXT += "%s\n" % ' '.join(result) message = messageTemplate % (FROM, ", ".join(TO), SUBJECT, TEXT) server = smtplib.SMTP(SERVER) #sys.stderr.write("message: `%s`\n" % message) server.sendmail(FROM, TO, message) server.quit() def extractForecast(soup): tdDates = soup.findAll("div", { "class" : "tdDate" }) tdForecasts = soup.findAll("div", { "class" : "tdForecast" }) tdTemps = soup.findAll("div", { "class" : "tdTemps" }) tdPrecips = soup.findAll("div", { "class" : "tdPrecip" }) results = [] for i in range(0, 10): date = tdDates[i].contents[2].contents[2] forecast = tdForecasts[i].contents[2].contents[2] temperature = tdTemps[i].contents[2].contents[0].string. \ replace("°", " degrees F") precipitation = tdPrecips[i].contents[2].string. \ replace("%", "% chance of rain") results.append([ date, forecast, temperature, precipitation ]) return results def getWeather(url): page = urllib2.urlopen(url) soup = BeautifulSoup(page) return soup if __name__ == "__main__": soup = getWeather(url) results = extractForecast(soup) sendEmail(results) # ChangeLog # 29th April 2008 - 0.1 - richb - Initial version.