On this page
  1. html
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Extracting Links with html.parser.HTMLParser
  7. Gotchas & Boundaries
  8. Common Functions

html

Prev: hmac | Up: stdlib_module | Next: http
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — html
Tags: #public #python3 #stdlib


Import

import html

Overview

HTML character entity escaping (html.escape, html.unescape) plus the streaming html.parser.HTMLParser base class. Always call html.escape() on untrusted text interpolated into HTML templates; use html.parser.HTMLParser for lightweight zero-dependency HTML extraction.

Quick Start

import html

safe = html.escape('<script>alert("xss")</script>', quote=True)
assert safe == "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"
assert html.unescape("5 &lt; 10 &amp; &#x27;ok&#x27;") == "5 < 10 & 'ok'"

Implementation Walkthrough

from html.parser import HTMLParser

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

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if tag == "a":
            for k, v in attrs:
                if k == "href" and v:
                    self.links.append(v)

parser = LinkExtractor()
parser.feed('<p><a href="https://example.org">Home</a></p>')
parser.close()
assert parser.links == ["https://example.org"]

Gotchas & Boundaries

Common Functions

Linked from

Related notes