parserino

HTML5 parser and DOM manipulation library.

Parserino is a fast html5 parser and DOM manipulation library written in pure D (born as a D port of the lexbor library, from which the tree construction is derived).

import parserino;
void main()
{
   auto doc = Document("<html><body><p>Hello World!</p></body></html>");
   assert(doc.body.firstChild.textContent == "Hello World!");
   assert(doc.byTagName("p").front.textContent == "Hello World!");
}

LLM-friendly documentation: llms.txt, the whole API in llms-full.txt, a skill for agents in SKILL.md.

The main types are Document, Node and Element:

  • a Node is any node of the tree: an element, a text, a comment, a doctype, ...;
  • an Element is a node that is an element: it adds attributes, innerHTML, matches, ... It converts implicitly to Node; node.asElement goes the other way.

Navigation: one method for each direction, with the kinds of nodes to see as a template parameter (Show, as whatToShow in the DOM). The default is Show.Element, and then the result is an Element (or a range of Element); with other filters it's a Node.

p.children                           // the child elements
p.children!(Show.All)                // all the child nodes
doc.descendants!(Show.Comment)       // all the comments of the document
p.firstChild!(Show.Text)             // the first child text node
doc.body.descendants.retro           // reverse document order

Errors: searches and navigation give an invalid node (== null, isValid is false) or an empty range when nothing is found; a node that can't have children (a text, a comment) just has no children. Calling a method on an invalid node or document, or a mutation that is not possible (a child of a text, a node inside itself, a node of another document, a sibling of a node without parent), throws a ParserinoException.

Views: the getters that copy a string stored in the document have a ...View variant that returns a slice of the document memory instead (localNameView, idView, getAttributeView, classesView, attributesView, dataView). The slice is valid until that value changes or the document is destroyed. Computed values (textContent of an element, innerHTML, title) have no view.

Memory: the tree of a Document (malloc'd) is freed by the GC when no Document, Node or Element reaches it anymore, also when they are kept in GC memory (arrays, closures, ...). Every Node keeps its document alive, so nodes are always safe to use, even after the Document variable goes out of scope. Nodes removed from the tree stay valid (they are released with their document). The GC doesn't see the memory of the trees: when it has grown too much since the last collection, a new document triggers one first.

Lazy parsing: Document(html, Parsing.Lazy) builds the tree only as far as your queries need. doc.byClass("x").take(3) stops parsing a little after the third match.

Input: the html must be UTF-8 (invalid bytes become U+FFFD, a BOM is removed). For other encodings see parserino.encoding.toUtf8.

Types 15

enumShow : uint

The kinds of nodes that a navigation or a range gives: the same bits of NodeFilter.whatToShow in the DOM. Combine them with `|`: children!(Show.Text | Show.Comment).

Element = 0x1elements
Text = 0x4text nodes
CDataSection = 0x8CDATA sections
ProcessingInstruction = 0x40processing instructions (`<?target data>`)
Comment = 0x80comments
Document = 0x100the document
DocumentType = 0x200the doctype
DocumentFragment = 0x400document fragments
All = 0xFFFF_FFFFall the nodes
classParserinoException : Exception

Thrown on invalid operations (invalid node, impossible mutation, bad selector, ...)

Constructors
this(string msg, string file = __FILE__, size_t line = __LINE__)An exception with a message, thrown at `file`:`line`

How Document parses its input

EagerParse everything at once
LazyParse chunk by chunk, only as far as queries and accessors need

Options of the parser (see Document.this)

Fields
Parsing parsing
size_t chunkSize
bool scriptingParse as a browser with scripting enabled: the content of `<noscript>` is text. Off by default, so the content of `<noscript>` is parsed as html (useful for scraping).
bool collectErrorsCollect the parse errors (see `Document.parseErrors`). Off by default: then they cost nothing. With `ctDocument` the parse errors become compile errors.

A parse error: the html is not valid (the parser recovers anyway, as a browser does). The codes of the tokenizer are the ones of the HTML standard; the standard doesn't name the errors of the tree construction, so they have codes in the same style (misnested-tag, ...).

Fields
size_t line
size_t column
Methods
string name() @property const @safe nothrow pure @nogcThe name of the error: `"unexpected-null-character"`, `"missing-doctype"`, ...
string toString() const @safe pure`"line:column: name"`
structDocument

The HTML5 Document

Methods
Document opAssign(Document rhs) ref returnCopies share the same document (freed by the GC when nothing uses it anymore)
Document opAssign(const(char)[] html) ref returnParse `html` into a new document: `doc = "<html>...";`
Document opAssign(typeof(null)) ref return`doc = null` releases the document: `doc` becomes invalid
bool opEquals(typeof(null)) const @safe nothrow pure`doc == null` is true for an invalid document, `doc == "..."` compares the html of the document, `doc == other` is true if they are copies of the same document.
bool opEquals(D)(auto ref const D d) constditto
bool isValid() @property const @safe nothrow pure @nogcIs this a valid html5 document?
bool isParsing() @property const @safe nothrow pure @nogcIs the document still being parsed? (see `Parsing.Lazy`)
size_t bytesParsed() @property const @safe nothrow pure @nogcNumber of input bytes given to the parser so far
void finishParsing()Complete the parsing of a lazy document. It does nothing on a fully parsed one.
ParseError[] parseErrors() @propertyThe parse errors, in the order of the input (it completes the parsing). They are collected only with `ParseOptions.collectErrors`, else the list is empty. The errors of the tree construction are at...
Document dup()A deep copy of the document, independent from this one
Snapshot snapshot() @propertyA compact copy of the tree: `Document(snapshot)` rebuilds a document from it without parsing, many times faster. Parse a template once, then make many documents from it. (`ctDocument` does the same...
string toString() constReturn document as html string
void toString(scope void delegate(const(char)[]) sink) constWrite the document as html to a sink
string toPrettyString() constThe document as indented html, to read it: each block element on its own line, two spaces for each level; elements with only text and inline elements stay on one line. The whitespace between the no...
void toString(W)(ref W writer) if (isOutputRange!(W, const(char)[]) && !is(W : void delegate(const(char)[]))) constditto
string title() @propertyThe content of `<title>`, with the whitespace stripped and collapsed (as in the DOM)
string rawTitle() @propertyditto, without whitespace normalization
void title(const(char)[] s) @propertySet the content of `<title>` tag
Element createElement(const(char)[] tagName)Create a html element
Node createText(const(char)[] text)Create a text node
Node createComment(const(char)[] text)Create a comment
Node node() @propertyThe document as a `Node` (for the functions that take any node)
Element documentElement() @propertyThe `<html>` element
Element body() @propertyThe `<body>` element: the first `<body>` or `<frameset>` child of `<html>`, as in the DOM
Element head() @propertyThe `<head>` element
Element byId(const(char)[] id)Get an element by id. It returns an invalid element (`== null`) if not found.
auto byClass(string name)A lazy range of elements filtered by class
auto byTagName(string name)A lazy range of elements filtered by tag name (`"*"`: all the elements)
auto byComment(string text)A lazy range of the comments with this text (whitespace at the ends ignored)
auto byCommentExact(string text)A lazy range of the comments with exactly this text
auto bySelector(const(char)[] selector)A lazy range of elements filtered using a css selector
auto bySelector(Selector selector)ditto
auto bySelector(string css)()ditto, parsed at compile time
auto children(Show show = Show.Element)()The children of the document (the doctype, the `<html>` element, comments, ...)
auto descendants(Show show = Show.Element)()All the nodes of the document, in tree order
string opCast(T : string)() constYou can cast a document to a string
Node fragment(const(char)[] html, const(char)[] context = "body")Parse a fragment of html. The result is a `DocumentFragment` node, not attached to the document: inserting it (`append`, `before`, ...) moves its children.
Constructors
this(const(char)[] html, Parsing parsing = Parsing.Eager, size_t chunkSize = DefaultChunkSize)Parse a document. With `Parsing.Lazy` the tree is built chunk by chunk (`chunkSize` bytes), only when a query or an accessor needs more of it. The results are always the same as for a fully parsed ...
this(const(char)[] html, ParseOptions options)ditto
this(string html, Parsing parsing = Parsing.Eager, size_t chunkSize = DefaultChunkSize)ditto (an immutable string is not copied by the lazy parsing)
this(string html, ParseOptions options)ditto
this(Snapshot snapshot)Rebuild a document from a snapshot (see `snapshot`): much faster than parsing again. Each call gives a new, independent document.
structSnapshot

A compact copy of a document tree, made by Document.snapshot: Document(snapshot) makes new documents from it without parsing. It can be shared between threads.

Methods
bool isValid() @property const @safe nothrow pure @nogcIs this a snapshot of a document?
structNode

A node of a document: an element, a text, a comment, a doctype, the document itself, ... See the module documentation for the navigation (Show) and the rules on errors.

Methods
Document ownerDocument() @propertyThe document of this node
bool isValid() @property const @safe nothrow pure @nogcIs this a valid node?
NodeType nodeType() @property constThe type of the node (`NodeType.Element`, `NodeType.Text`, ...)
string nodeName() @propertyThe name of the node, as in the DOM: the tag name for elements (uppercase for html elements: `"DIV"`), `"#text"`, `"#comment"`, `"#document"`, `"#document-fragment"`, the name of a doctype, the tar...
bool isElement() @property const @safe nothrow pure @nogcIs this node an element?
bool isText() @property const @safe nothrow pure @nogcIs this a text node?
bool isComment() @property const @safe nothrow pure @nogcIs this a comment?
Element asElement()This node as an `Element`, or an invalid element if it isn't one
string textContent() @propertyThe text of the node (DOM `textContent`): the text of all the descendants for elements and fragments, the data for texts, comments and processing instructions, `null` for the document and the doctype.
void textContent(const(char)[] text) @propertySet the text: for elements and fragments it replaces all the children with a text node, for texts, comments and processing instructions it replaces the data. It does nothing on the document and the...
const(char)[] dataView() @propertyThe data of a text, comment or processing instruction without copying it; `null` for other nodes
auto parent(Show show = Show.Element)()The parent, if it matches `show` (else an invalid node). By default the parent element: the parent of `<html>` is the document, so `html.parent` is invalid and `html.parent!(Show.All)` is the docum...
auto firstChild(Show show = Show.Element)()The first child that matches `show`
auto lastChild(Show show = Show.Element)()The last child that matches `show`
auto nextSibling(Show show = Show.Element)()The next sibling that matches `show`
auto previousSibling(Show show = Show.Element)()The previous sibling that matches `show`
auto children(Show show = Show.Element)()The children that match `show`, as a lazy (bidirectional) range
auto descendants(Show show = Show.Element)()All the descendants that match `show`, in tree order, as a lazy (bidirectional) range
bool hasChildNodes()Does this node have children? (any kind of node)
bool contains(Node other)Is `other` this node or one of its descendants? (as in the DOM)
Element byId(const(char)[] id)Search for an element by id. It returns an invalid element (`== null`) if not found.
auto byClass(string name)Search for elements by class See_also: `parserino.Document.byClass`
auto byTagName(string name)Search for elements by tag name (case-insensitive for html elements; `"*"` gives all the elements) See_also: `parserino.Document.byTagName`
auto byComment(string text)Search for comments by text (whitespace at the ends ignored) See_also: `parserino.Document.byComment`
auto byCommentExact(string text)Search for comments with exactly this text
auto bySelector(const(char)[] selector)Search for elements by css selector See_also: `parserino.Document.bySelector`
auto bySelector(Selector selector)ditto
auto bySelector(string css)()ditto, parsed at compile time
void append(E)(auto ref E what)Append a node (or a text, or a fragment) as the last child. Strings become text nodes; `"<b>x</b>".asFragment` is parsed as html (in the context of this element); a `DocumentFragment` (see `Documen...
void prepend(E)(auto ref E what)Insert a node (or a text, or a fragment) as the first child
void before(E)(auto ref E what)Insert a node (or a text, or a fragment) before this one
void after(E)(auto ref E what)Insert a node (or a text, or a fragment) after this one
void replaceWith(E)(auto ref E what)Replace this node with another one (or with a text, or a fragment)
void appendChild(Node child)Append a child node (as `append`, only for nodes)
void opOpAssign(string op : "~", E)(auto ref E what)`node ~= x` is `node.append(x)`
bool remove()Remove this node from its parent. The node is still valid and can be inserted again. It returns false if the node had no parent.
Node dup()A deep copy of this node (with all the descendants), not attached to the document
Node shallowDup()A copy of this node alone (for an element: the tag and the attributes, without children)
string toString() constThe node as html (for an element: `outerHTML`)
void toString(scope void delegate(const(char)[]) sink) constWrite the node as html to a sink
string toPrettyString() constThe node as indented html, to read it (see `Document.toPrettyString`)
void toString(W)(ref W writer) if (isOutputRange!(W, const(char)[]) && !is(W : void delegate(const(char)[]))) constditto
string opCast(T : string)() const`cast(string) node` is the same as `toString`
bool opEquals(typeof(null)) const @safe nothrow pure @nogc`node == null` is true for an invalid node, `node == "..."` compares the html of the node, `node == other` is true if they are the same node.
bool opEquals(E)(auto ref const E e) constditto
size_t toHash() const nothrow @safeNodes can be keys of associative arrays (the same node, the same key)
Node opAssign(typeof(null)) ref return`node = null` makes it an invalid node (it releases its document)
Constructors
this(ref Document doc, DomNode * raw)
structElement

A node that is an element. It converts implicitly to Node.

Fields
Node node
Methods
string localName() @propertyThe local name, as in the DOM: `"div"`, `"foreignObject"`
const(char)[] localNameView() @propertyditto, without copying
string tagName() @propertyThe tag name, as in the DOM: uppercase for html elements (`"DIV"`), else the local name
bool isEmpty() @propertyIs this element empty? No element and no text children (comments don't count), as `:empty`
bool isBlank() @propertyLike `isEmpty`, but whitespace text doesn't count either, as `:blank`
AttributeRange!false attributes() @propertyReturn a lazy range of attributes for this element
AttributeRange!true attributesView() @propertyditto, without copying names and values
bool hasAttribute(const(char)[] attr)Check if an attribute exists
void removeAttribute(const(char)[] attr)Remove an attribute from this element
void setAttribute(const(char)[] name, const(char)[] value)Set an attribute for this element
string getAttribute(const(char)[] attr)Get an attribute. It returns `null` if the attribute is missing.
const(char)[] getAttributeView(const(char)[] attr)ditto, without copying
string id() @propertyThe id of this element (empty if missing)
const(char)[] idView() @propertyditto, without copying
void id(const(char)[] value) @propertySet the id of this element
ClassRange!false classes() @propertyAll the classes of this element
ClassRange!true classesView() @propertyditto, without copying
Element dup()A deep copy of this element, not attached to the document
Element shallowDup()A copy of this element alone: the tag and the attributes, without children
void copyFrom(Element e)Make this element a copy of another one: the tag, the attributes and the children
void shallowCopyFrom(Element e)Make this element a copy of another one, without the children: the tag and the attributes
void innerHTML(const(char)[] html) @propertySet the html content of this element (for a `<template>`: its content)
string innerHTML() @propertyGet the html content of this element
string innerText() @propertyThe text of the element (the same as `textContent`: here nothing depends on the layout)
void innerText(const(char)[] text) @propertySet the text of the element (the same as `textContent`)
string outerHTML() @propertyThe outer html of this element
void outerHTML(const(char)[] html) @propertyReplace this element with the html (parsed in the context of the parent)
string startTag() @propertyThe start tag of this element, with its attributes: `<a href="x">`
bool matches(const(char)[] selector)Does this element match a css selector?
bool matches(Selector selector)ditto
Element opAssign(const(char)[] html) ref returnReplace this element with the (single) element parsed from `html`: `el = "<b>x</b>";`
Element opAssign(typeof(null)) ref return`element = null` makes it an invalid element (it releases its document)
Element opAssign(Element rhs) ref returnCopies refer to the same element
Constructors
this(ref Document doc, DomNode * raw)
this(Node n)
Nested Templates
AttributeA simple key/value struct representing a html attribute
AttributeViewditto, as slices of the document memory (see `attributesView`)
structAttributeRange(bool view)

A range of attributes. It keeps the document alive.

Methods
bool empty() @property const @safe nothrow pure @nogc
@property auto front()
void popFront()
AttributeRange save() @property
structClassRange(bool view)

A range of the classes of an element (classes, classesView). It keeps the document alive.

Methods
bool empty() @property const @safe nothrow pure @nogc
@property auto front() const
void popFront()
ClassRange save() @property
Constructors
this(Document doc, const(char)[] classes)
structSelector

A compiled css selector. It can be used with any document, many times.

auto sel = Selector("div > a[href]");
foreach (doc; documents)
   foreach (link; doc.bySelector(sel)) { ... }

Methods
Selector opAssign(Selector rhs) ref returnCopies share the same compiled selector
bool isValid() @property const @safe nothrow pure @nogcIs this a valid (compiled) selector?
Constructors
this(const(char)[] selector)Compile a selector. It throws on invalid syntax.
Destructors
structNodeRange(Filter, Show show)

A lazy range of nodes in tree order (or in reverse tree order). It is returned by descendants, children, byTagName, byClass, bySelector, ... It is a forward range: save gives an independent copy. A lazy range of nodes in tree order: descendants, children, byTagName, byClass, bySelector, ... return it. It's a bidirectional range: save gives an independent copy, back/popBack (and so retro) go in reverse document order. The elements are Elements if show is Show.Element, else Nodes.

Methods
bool empty() @property
NodeOf!show front() @property
void popFront()
NodeOf!show back() @property
void popBack()
typeof(this) save() @property
Constructors
this(ref Document doc, DomNode * root, bool deep, Filter filter)
structWalkStep(Show show)

A step of walk: the walk enters or leaves node

Fields
NodeOf!show node
bool enter
Methods
bool leave() @property const @safe nothrow pure @nogcLeaving an element, after its children
structWalkRange(Show show, alias descend)

The range of walk

Methods
bool empty() @property
WalkStep!show front() @property
void popFront()
WalkStep!show back() @property
void popBack()
typeof(this) save() @property
Constructors
this(ref Document doc, DomNode * root)

Functions 6

fnbool isValidSelector(const(char)[] css) @nogc nothrowIs this a valid css selector? It works at compile time too.
fnauto frontOrThrow(T)(T range) if (isInputRange!T)Get the first element of a range or throw an exception
fnauto frontOr(T, El)(T range, El fallback) if (isInputRange!T && is(El == ElementType!T))Get the first element of a range or return the second args
fnauto frontOrInit(T)(T range) if (isInputRange!T)Get the first element of a range, or its `init` (an invalid node for the ranges of nodes)
fnauto asFragment(string s)Create a fragment from a string. The fragment is not attached to any document by default. The fragment is not a valid element or document, it's just a piece of html you can add to a document.
fnauto walk(Show show = Show.Element, alias descend = e => true, T)(T root) if (is(T : Node) || is(T == Document))A visit of the descendants of `root` in tree order, entering and leaving each element: an element gives a step with `enter` before its children and one with `leave` after them, the other nodes give...

Variables 1

enumvarDefaultChunkSize = 16 * 1024

Default chunk size for Parsing.Lazy

Templates 3

tmplctSelector(string css)

A selector parsed at compile time: syntax errors are compile errors.

auto links = doc.bySelector(ctSelector!"nav > a[href]");
auto same = doc.bySelector!"nav > a[href]";

Functions
Selector ctSelector()
tmplctDocument(string html, ParseOptions options = ParseOptions.init)

A document parsed at compile time. The compiler parses html once and stores the tree in the executable. At runtime each call returns a new document (mutable, independent from the others) copied from that tree, without tokenizing or building it again.

auto page = ctDocument!(import("page.html"));   // needs -J with the path of page.html
page.byId("title").textContent = "Hello";

With options.collectErrors the html is validated at compile time: any parse error is a compile error that lists them. The other options don't matter here.

enum ParseOptions strict = { collectErrors: true };
auto page = ctDocument!(import("page.html"), strict);   // doesn't compile if page.html is not valid html

CTFE needs compiler memory and time: some tens of KB take about 1 s, a 600 KB page about 1 GB and 10 s (dmd).

Functions
Document ctDocument()
tmplNodeOf(Show show)

The result of a navigation with the filter show: Element for Show.Element, else Node