CL-HTTP Chapter 15: HTML Parser


Reference Manual | Prev: Chapter 14. W4 Web Walker | Next: Chapter 16. Lambda-IR Information Retrieval


Contents

  1. 15.1 Overview
  2. 15.2 Parsing
  3. 15.3 DOM Access
  4. 15.4 DTD Support
  5. 15.5 Integration

15.1 Overview

The CL-HTTP HTML Parser (version 12) is a DTD-driven parser that reads HTML documents into structured parse trees of CLOS objects. It supports HTML 2.0, HTML 3.2, HTML 4.0 (strict, transitional, and frameset), and HTML5. The parser uses metadata from the loaded DTD to determine element containment, implicit open/close tags, and content models, producing a correct parse tree even for malformed HTML.

The parser lives in the :HTML-PARSER package. When loaded within CL-HTTP (indicated by the :cl-http feature), it integrates with CL-HTTP's tokenizer (:TK1), property list mixin, and JSON serialization via :ST-JSON. It can also be used standalone with its own tokenizer and property list implementations.

Key capabilities:

15.2 Parsing

The primary parsing interface is parse-document, a generic function that retrieves and parses an HTML resource, returning a parsed-document instance that captures both the parse tree and retrieval metadata.

Parsing from Files

;; Parse a local HTML file
(html-parser:parse-document #p"/path/to/page.html")
=> #<PARSED-DOCUMENT /path/to/page.html 47 tags 3ms>

;; Parse with a specific DTD and retain the raw source
(html-parser:parse-document #p"/path/to/page.html"
                            :dtd "HTML5"
                            :retain-source t)

Parsing from URLs

;; Parse a remote page (requires CL-HTTP client)
(html-parser:parse-document "http://www.example.com/page.html")
=> #<PARSED-DOCUMENT http://www.example.com/page.html 123 tags 45ms>

Parsing from Strings

;; Low-level: parse an HTML string directly
(html-parser:initialize-parser "HTML5")
(html-parser:simple-parser "<html><body><p>Hello</p></body></html>")

The parsed-document Class

A parsed-document object captures both the parse result and retrieval metadata:

(html-parser:document-url doc)
URL string or pathname of the parsed resource.
(html-parser:document-scheme doc)
URL scheme keyword: :http, :https, :file, or :ftp.
(html-parser:document-access-time doc)
Universal time when the resource was retrieved.
(html-parser:document-content-type doc)
MIME content type string from the response headers.
(html-parser:document-status-code doc)
HTTP status code, or nil for file/ftp access.
(html-parser:document-parse-tree doc)
Root abstract-tag-instance of the parse tree.
(html-parser:document-parse-time-msec doc)
Wall-clock parse time in milliseconds.
(html-parser:document-tag-count doc)
Total number of tags in the parse tree.
(html-parser:document-source doc)
Raw HTML string, or nil if not retained.
(html-parser:document-dtd doc)
DTD doctype string used for parsing.

15.3 DOM Access

The parse tree consists of nested abstract-tag-instance objects. Each tag instance has a name, attributes, and child parts (which may be other tag instances or strings representing PCDATA).

Tag Instance Accessors

(html-parser:name tag)
The tag name token (e.g., the token for P, DIV, A).
(html-parser:attr-values tag)
Association list of attribute name-value pairs.
(html-parser:parts tag)
List of child elements: tag instances and strings.
(html-parser:part-of tag)
Parent tag instance.
(html-parser:instance-of tag)
The DTD tag definition for this instance.
(html-parser:html-fragment tag)
The raw HTML fragment associated with this tag.

DOM Registry

The DOM registry manages a collection of parsed documents by name, enabling retrieval and release:

(html-parser:parse-and-register url name &key dtd)
Parse the document at url and register it under name.
(html-parser:find-document name)
Retrieve a registered document by name.
(html-parser:release-document name)
Remove a document from the registry.
(html-parser:list-documents)
List all registered document names.

Structure Extraction

(html-parser:document-title doc)
Extract the document title string.
(html-parser:document-outline doc)
Extract the heading structure as a nested outline.
(html-parser:document-links doc)
Extract all hyperlinks from the document.
(html-parser:document-text doc)
Extract the text content, stripping all markup.
(html-parser:document-tree doc)
Return the parse tree in a simplified list representation.
(html-parser:document-find doc tag-name)
Find all instances of a given tag in the document.
(html-parser:count-parse-tree-tags node)
Count all tag instances in a parse tree.

15.4 DTD Support

The parser uses compiled DTD definitions that specify element containment rules, attribute definitions, entity declarations, and content models. The DTD determines how the parser handles implicit open/close tags, unknown elements, and validation.

Available DTDs

The variable html-parser:*html-dtd-list* lists the available DTDs:

Doctype IdentifierDescription
"HTML5"HTML5 (default) — extends HTML 4.0 Transitional with HTML5 sectioning, grouping, inline, and media elements
"-//W3C//DTD HTML 4.0 Transitional//EN"HTML 4.0 Transitional
"-//W3C//DTD HTML 4.0 Frameset//EN"HTML 4.0 Frameset
"-//W3C//DTD HTML 4.0//EN"HTML 4.0 Strict
"-//W3C//DTD HTML 3.2 Draft//EN"HTML 3.2
"-//IETF//DTD HTML 2.0//EN"HTML 2.0

Initializing the Parser

;; Initialize with the default DTD (HTML5)
(html-parser:initialize-parser)

;; Initialize with a specific DTD
(html-parser:initialize-parser "-//W3C//DTD HTML 4.0//EN")

initialize-parser compiles and loads the DTD if needed, sets up tag containment backpointers, defines the unknown-tag handler, and initializes the parse dispatch functions. The current DTD is stored in html-parser:*current-dtd*.

HTML5 DTD Elements

The HTML5 DTD extends HTML 4.0 Transitional with these element groups:

Extending the DTD

;; Define a new entity group
(html-parser:define-html-entity #e"%my-elements"
  (:or custom-widget data-grid))

;; Define a custom element
(html-parser:define-html-element custom-widget
  :content (* #e"%flow")
  :attributes (#e"%attrs"))

;; Register a new DTD
(html-parser:modify-dtd-list "My-DTD" "my-dtd-file")

15.5 Integration

Integration with W4 Web Walker

The HTML parser integrates with W4 for web scraping workflows. Parse documents retrieved by the walker, extract structure, and apply constraints based on HTML content:

;; Walk a site, parsing each page
(w4:with-activity ("scrape"
                   (:report-stream '*standard-output*)
                   :constraints '((depth 2)
                                  (no-cycles)
                                  (header-content-type (:text :html)))
                   :actions '((trace) (generate-inferiors)))
  ;; Within a custom action, parse retrieved content:
  ;; (html-parser:parse-document url)
  (walk "http://www.example.com/" activity))

JSON Serialization for LLM Integration

When CL-HTTP is loaded with ST-JSON support, parsed documents can be serialized to JSON for consumption by language models:

(html-parser:document-to-lisp doc)
Convert the parse tree to a nested Lisp list representation.
(html-parser:document-to-html doc)
Regenerate HTML source from the parse tree.
(html-parser:write-document-source doc stream)
Write the document source (original or regenerated) to a stream.

Validation

(html-parser:validate-and-register url name)
Parse, validate against the DTD, and register. Validation messages are collected in html-parser:*validation-messages*.

Parser Configuration

html-parser:*current-dtd*
The currently loaded DTD doctype string, or nil.
html-parser:*dtd-tags*
The tag definition table for the current DTD.
html-parser:*dtd-toplevel-tags*
Tags that can appear at the top level of the document.