CSC111 Lab 9 Solution Programs

From dftwiki3
Revision as of 12:31, 29 April 2010 by Thiebaut (talk | contribs) (Weather)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 17:30, 29 April 2010 (UTC)


Weather

# 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 sandwiched between
# the two constants BEGINSECTION and ENDSECTION
#

import urllib2
import sys

#--- some constants used by the program ---
BASEURL = "http://www.weather.com/weather/today/%s"
BEGINSECTION = '<div class="ccTemp">'
ENDSECTION = "&deg;"


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 "Temperature 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()