''' Purpose: provide weather forecast by accessing US Weather Service web service Usage: user provides a zipcode Output: current forecast for that zipcode ''' # get url access capability from cs 1112 module import url # define weather.gov base query # https - s = secure website WEATHER_GOV_QUERY = "https://forecast.weather.gov/zipcity.php?inputstring=" # forecast delimiters -- these will help us locate where the forecast is -- between the front_delimiter # and end_delimiter FRONT_DELIMITER = "
" # text that precedes forecast REAR_DELIMITER = "
" # text that follows forecast # delimiter lengths LENGTH_FRONT_DELIMITER = len( FRONT_DELIMITER ) # we need the length of the front delimiter # b/c the forecast starts RIGHT AFTER the front_delimiter # not where the front_delimiter starts LENGTH_REAR_DELIMITER = len( REAR_DELIMITER ) # get zipcode of interest reply = input( "Enter zipcode: " ) zipcode = reply.strip() # clean-up response: clean whitespaces # specify complete query query_link = WEATHER_GOV_QUERY + zipcode # get the complete link to that zip code on the National Weather # Service website # get response from weather.gov page = url.get_contents( query_link ) # get_contents() is a function within the url module # gives it a string that is a link for a website # then gives us back the content of the website # print( page ) # to get the forecast, we need to find it within the page # start by finding the forecast delimiters front_index = page.find( FRONT_DELIMITER ) # at what index does the FRONT_DELIMITER start in the string page? # for strings, we use find() to get the index of the argument rear_index = page.find( REAR_DELIMITER, front_index ) # find the index at which the END_DELIMITER starts # second parameter -- find the REAR_DELIMITER starting from the front_index # print( front_index, rear_index ) # print where the FRONT_DELIMITER starts, where the REAR_DELIMITER starts # after the index of the FRONT_DELIMITER # (mis)try to use those index delimiters to pick off the forecast # want a slice from page where the forecast starts forecast = page[ front_index : rear_index ] # includes from front_index and up to but not including rear_index # but if we start at front_index, we also include the FRONT_DELIMITER string --> we want the index # AFTER the FRONT_DELIMITER --> so we add the LENGTH of the FRONT_DELIMITER # if the front_index is 2, and the front_delimiter has length 5 --> the forecast actually starts at index 7 # since that is after the entire front_delimiter string # so we add 2 and 5 = 7 --> 7 is the index where the forecast starts print( forecast ) # this version, since it only starts at front_index, also includes the FRONT_DELIMITER print() # get the indices for the front and rear of the forecast forecast_start = front_index + LENGTH_FRONT_DELIMITER forecast_rear = rear_index # ready to get and print the forecast forecast = page[ forecast_start : forecast_rear ] # print the forecast print( forecast )