The HTMLParser Module

(New in 2.2) An improved HTML parser. Can be used to replace sgmllib, in many cases.

Like the other parsers in the standard library, this parser implements the standard feed/close consumer protocol, and calls methods on itself to handle the various parts of the HTML document. To use the parser, create a subclass where you override the methods you’re interested in.

This example extracts anchor links from an HTML document:

import HTMLParser

class AnchorParser(HTMLParser.HTMLParser):

    def __init__(self):
        self.anchors = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            for k, v in attrs:
                if k == "href":

f = open("sample.html")

p = AnchorParser()

print p.anchors

Here’s an alternate driver that lets you iterate over the anchors, as they are found by the parser:

class AnchorParser:

def getanchors(file):
    p = AnchorParser()
    while 1:
        # get some data from the source
        s =
        if s:
        # return anchors to caller
        for anchor in p.anchors:
            yield anchor
        if not s:
        p.anchors[:] = [] # reset the list

# read from a file
for anchor in getanchors(open("index.html")):
    print anchor

# read from a remote site
from urllib import urlopen
for anchor in getanchors(urlopen("")):
    print anchor

A Django site. rendered by a django application. hosted by webfaction.