Examples of using the html parser

Miki Tebeka miki.tebeka at zoran.com
Thu Mar 4 12:17:43 CET 2004


Hello Boogie,

> Were can I find examples of the usege of the html parser class?
Here is what I do to find the current price of a quote in Yahoo!
class Parser(HTMLParser):
     '''HTML Parser to get quote value'''
     def __init__(self, quote):
         HTMLParser.__init__(self)
         self.state = "START"
         self.value = ERR_VALUE
         self.quote = quote.upper()

     def handle_starttag(self, tag, attrs):
         '''Handle start tag'''
         if self.state == "AFTER_START" and tag == "b":
             self.state = "GET"

     def handle_data(self, data):
         '''Handle tag data'''
         if self.state == "START" and data == "Last Trade:":
             self.state = "AFTER_START"
         elif self.state == "GET":
             try:
                 self.value = float(data)
             except ValueError:
                 self.value = ERR_VALUE
             self.state = "DONE"

def get_quote(quote):
     '''Get quote prices'''
     p = Parser(quote)
     p.feed(urlopen("http://finance.yahoo.com/q?s=%s" % 
quote.upper()).read())
     return p.value


HTH.
Miki



More information about the Python-list mailing list