Examples of using the html parser

  • Thread starter Boogie El Aceitoso
  • Start date
M

Miki Tebeka

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
 
N

Ng Pheng Siong

According to Boogie El Aceitoso said:
Were can I find examples of the usege of the html parser class?

M2Crypto has an example in demo/ssl/sess.py. Here's the docstring:

"""M2Crypto.SSL.Session client demo: This program requests a URL from
a HTTPS server, saves the negotiated SSL session id, parses the HTML
returned by the server, then requests each HREF in a separate thread
using the saved SSL session id."""

Note that the code simply instantiates a parser and feeds it the HTML; it
doesn't apply any parsing-related callback.
 
J

John J. Lee

Boogie El Aceitoso said:
Were can I find examples of the usege of the html parser class?

Simpler to use, for simple cases:

http://wwwsearch.sf.net/pullparser/


Note that the example in the tarball that does something like

try:
parser.get_compressed_text(endat=("endtag", "a"))
except NoMoreTokensError:
...

Is out of date: .get_text() and .get_compressed_text() now return an
empty string instead.


John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,184
Messages
2,570,973
Members
47,530
Latest member
jameswilliam1

Latest Threads

Top