MrPolywhirl

ScrapeHoodCal.py

Oct 30th, 2013
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.88 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. from bs4 import BeautifulSoup
  4. import pprint
  5. import re
  6. import StringIO
  7. import sys
  8. import urllib2
  9.  
  10. MONTHS = ['January','February','March','April','May','June',\
  11. 'July','August','September','October','November','December']
  12. DAYS_OF_WEEK = ['Monday','Tuesday','Wednesday','Thursday',\
  13. 'Friday','Saturday','Sunday']
  14. REGEX_YEAR = '^([A-Z][a-z]+\s?\w+)\s+(\d{4})$'
  15. REGEX_DAY = '^([A-Z][a-z]{2,5}day)\s+(\d+)$'
  16.  
  17. '''
  18. Retrieve the text from a meta tag from the Hood College website.
  19. '''
  20. def retrieveText(url):
  21.     data = urllib2.urlopen(url)       # type 'instance
  22.     html = data.read()                # type 'str'
  23.     soup = BeautifulSoup(html)        # class BeautifulSoup.BeautifulSoup
  24.     resultSet = soup.findAll('meta',
  25.         attrs={"name":"Description"}) # class BeautifulSoup.ResultSet
  26.     tag = resultSet[0]                # class BeautifulSoup.Tag
  27.     ucode = tag['content']            # type 'unicode'
  28.  
  29.     return ucode.encode('utf-8').strip()
  30.  
  31. '''
  32. Create a dictionary given a block of text.
  33. '''
  34. def createDictionary(text, debug):
  35.     def console(frmt, *args, **kwargs):
  36.         if debug:
  37.             print(frmt.format(*args, **kwargs))
  38.  
  39.     aDict = {}
  40.     currYear, currMonth, currDay = None, None, None
  41.     i, ioStr = 0, StringIO.StringIO(text)
  42.     for rawLine in ioStr:
  43.         procLine = rawLine.strip().rstrip()
  44.         if procLine:
  45.             ### Test Year
  46.             m = re.search(REGEX_YEAR, procLine)
  47.             if m is not None:
  48.                 console('{:03d} Found Year -- {:s}', i, procLine)
  49.                 year = m.group(2)
  50.                 #year = procLine
  51.                 if not currYear == year:
  52.                     currYear, currMonth, currDay = year, None, None
  53.                 if currYear not in aDict:
  54.                     aDict[currYear] = {}
  55.                 continue
  56.                
  57.             ### Test Month
  58.             if currYear and procLine in MONTHS:
  59.                 month = MONTHS.index(procLine)
  60.                 if not month == currMonth:
  61.                     currMonth, currDay = month, None
  62.                 console('{:03d} Found Month -- {:s}', i, procLine)
  63.                 if currMonth is not None:
  64.                     if currMonth not in aDict[currYear]:
  65.                         aDict[currYear][currMonth] = {}
  66.                     continue
  67.            
  68.             ### Test Day
  69.             if currMonth:
  70.                 m = re.search(REGEX_DAY, procLine)
  71.                 if m is not None:
  72.                     dayOfWeek, day = m.group(1), '{:02d}'.format(int(m.group(2)))
  73.                     if not currDay == day:
  74.                         currDay = day
  75.                     console('{:03d} Found Day -- {:s}', i, procLine)
  76.                     if currDay not in aDict[currYear][currMonth]:
  77.                         aDict[currYear][currMonth][currDay] = {}
  78.                     continue
  79.            
  80.             #''' If the dictionary is ready, append the lines. ''''
  81.             if currDay:
  82.                 if not aDict[currYear][currMonth][currDay]:
  83.                     aDict[currYear][currMonth][currDay] = ''
  84.                 aDict[currYear][currMonth][currDay] += procLine + ' '
  85.  
  86.             i += 1
  87.    
  88.     return aDict
  89.  
  90. '''
  91. Write a dictionary object to a file with a specified indent level.
  92. '''
  93. def writeToFile(filename, aDict, indentLevel):
  94.     with open(filename, 'wt') as out:
  95.         pp = pprint.PrettyPrinter(indent=indentLevel,stream=out)
  96.         pp.pprint(aDict)
  97.  
  98. '''
  99. Main procedure for this script.
  100. '''
  101. if __name__ == '__main__':
  102.     if len(sys.argv) > 2:
  103.         print('Usage: ' + sys.argv[0] + ' {-d?}')
  104.         exit(0)
  105.  
  106.     debug = False
  107.     if len(sys.argv) == 2 and sys.argv[1] == '-d':
  108.         debug = True
  109.    
  110.     filename = 'output.txt'
  111.     html = retrieveText('http://www.hood.edu/calendar2013')
  112.     aDict = createDictionary(html, debug)
  113.     writeToFile(filename, aDict, 2)
  114.     print('Wrote JSON object to: ' + filename)
Advertisement
Add Comment
Please, Sign In to add comment