lolamontes69

Python/ HTMLParser example for searchengine.py

Jun 23rd, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. """ I haven't added this to searchengine.py yet, but I find this parses more forgivingly than BeautifulSoup. """
  2.    
  3.  
  4. from HTMLParser import HTMLParser
  5. import urllib2 as urllib2
  6. from string import punctuation
  7.  
  8. class MyHTMLParser(HTMLParser):
  9.  
  10.     count=0
  11.     head='active'
  12.     result=''
  13.    
  14.     def handle_starttag(self, tag, attrs):
  15.         if self.head=='passive':
  16.             if tag=='script':
  17.                 self.count=0
  18.         if tag=='title':
  19.             self.count=1
  20.  
  21.     def handle_endtag(self, tag):
  22.         if tag=="head":
  23.             self.count=1
  24.             self.head='passive'
  25.         if self.head=='passive':
  26.             if tag=='script':
  27.                 self.count=1
  28.         if tag=='title':
  29.             self.count=0
  30.            
  31.     def handle_data(self, data):
  32.         if self.count > 0:
  33.             self.result = self.result + data
  34.  
  35. def crawl(page):
  36.     try:
  37.         c = urllib2.urlopen(page)
  38.         parser = MyHTMLParser()
  39.         parser.feed(c.read())
  40.         return parser.result
  41.     except:
  42.         print 'Couldn\'t parse %s' % page
  43.  
  44. if __name__ == "__main__":
  45.     while 1+1==2:
  46.         page = str(raw_input('Enter URL to crawl >'))
  47.         result = crawl(page)
  48.         result = result.replace('\n',' ').replace('\t',' ').replace('\r',' ').lower()
  49.         result1 = result.split(' ')
  50.         for a in range(len(result1)):
  51.             if result1[a] in punctuation: result1[a] = ""
  52.             if result1[a][-1:] in punctuation:
  53.                 result1[a] = result1[a].replace('.', ' ')[:-1].lower()
  54.         for b in result1:
  55.             if b != '': print b,' ',
Advertisement
Add Comment
Please, Sign In to add comment