CSC111 getWeather.py

From CSclasswiki
Jump to: navigation, search

--Thiebaut 18:37, 20 April 2009 (UTC)


# getWeather.py
# D. Thiebaut
# This program goes to www.weather.com and gets the current temperature for
# a given zip code, which is obtained from the user.
# The program downloads the html text from www.weather.com and looks for
# the temperature that is embedded in an expression like this one:
# <div class="cCon"><strong class="obsTempTextA">53°F</strong><br/>
#

import urllib2
import sys

#--- some constants used by the program ---
BASEURL = "http://www.weather.com/outlook/travel/businesstraveler/local/%s"
BEGINSECTION = "\"obsTempTextA\">"
ENDSECTION = "°"


def getTemperature( zip ):
  # given a sign, the function fetches the astrology page for this                                                                       
  # sign and extracts the dates for the sign, and the "fortune"                                                                          

  url = BASEURL % ( zip.lower() )
  print url
  f = urllib2.urlopen( url )
  htmlText = f.read()
  #print htmlText

  beginIndex = htmlText.find( BEGINSECTION )
  endIndex   = htmlText.find( ENDSECTION, beginIndex )

  if beginIndex ==-1 or endIndex==-1:
      print "Error: beginIndex = %d endIndex = %d" \
            % ( beginIndex, endIndex )
      return "Dates not found", "Future not found"

  beginIndex = beginIndex + len( BEGINSECTION )
  temperature = htmlText[ beginIndex : endIndex ]
  return temperature

def main( ):
  #---- MAIN: gets zip code from user, fetches temperature, displays temperature ---
  zipCode =   raw_input( "enter zip code: " )
  temp = getTemperature( zipCode )
  print "The temperature in area %s is %s degrees" % (zipCode, temp )
  main()