HTMLParser calls methods as it encounters tags, data, comments, and entities. Its event model is lightweight and fits simple extraction from predictably generated HTML.

Practical example

from html.parser import HTMLParser

class LinkCollector(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self.links: list[str] = []

    def handle_starttag(self, tag, attrs) -> None:
        if tag == "a":
            href = dict(attrs).get("href")
            if href:
                self.links.append(href)

parser = LinkCollector()
parser.feed('<a href="/docs">Docs</a>')
print(parser.links)

Normalize collected values

Attributes arrive as pairs and may be missing. Resolve relative URLs against an approved base and validate schemes and hosts before making any request.

A parser is not a sanitizer

Real HTML may be malformed, and scripts can change the DOM after loading. HTMLParser does not run JavaScript or make content safe to render. Choose a dedicated tool for complex selectors or browser behavior.

Keep learning

Continue with Web Scraping with Python: BeautifulSoup and Selenium and Python Unicode, Bytes, and UTF-8: Practical Guide. A official Python documentation, accessed July 22, 2026, documents the API and behavior across versions.