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
Nodeis any node of the tree: an element, a text, a comment, a doctype, ...; - an
Elementis a node that is an element: it adds attributes,innerHTML,matches, ... It converts implicitly toNode;node.asElementgoes 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 orderErrors: 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
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).
Thrown on invalid operations (invalid node, impossible mutation, bad selector, ...)
this(string msg, string file = __FILE__, size_t line = __LINE__)An exception with a message, thrown at `file`:`line`How Document parses its input
Options of the parser (see Document.this)
Parsing parsingsize_t chunkSizebool 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, ...).
The HTML5 Document
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>...";`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 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 farvoid 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 oneSnapshot 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 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)[]))) constdittostring title() @propertyThe content of `<title>`, with the whitespace stripped and collapsed (as in the DOM)Element createElement(const(char)[] tagName)Create a html elementNode createText(const(char)[] text)Create a text nodeNode createComment(const(char)[] text)Create a commentElement body() @propertyThe `<body>` element: the first `<body>` or `<frameset>` child of `<html>`, as in the DOMElement 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 classauto 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 textauto bySelector(const(char)[] selector)A lazy range of elements filtered using a css selectorauto bySelector(Selector selector)dittoauto bySelector(string css)()ditto, parsed at compile timeauto 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 orderNode 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.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)dittothis(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)dittoA 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.
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.
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...Element asElement()This node as an `Element`, or an invalid element if it isn't onestring 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 nodesauto 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 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) rangeauto descendants(Show show = Show.Element)()All the descendants that match `show`, in tree order, as a lazy (bidirectional) rangebool 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 textauto bySelector(const(char)[] selector)Search for elements by css selector See_also: `parserino.Document.bySelector`auto bySelector(Selector selector)dittoauto bySelector(string css)()ditto, parsed at compile timevoid 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 childvoid before(E)(auto ref E what)Insert a node (or a text, or a fragment) before this onevoid after(E)(auto ref E what)Insert a node (or a text, or a fragment) after this onevoid 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 documentNode shallowDup()A copy of this node alone (for an element: the tag and the attributes, without children)void toString(W)(ref W writer) if (isOutputRange!(W, const(char)[]) && !is(W : void delegate(const(char)[]))) constdittobool 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.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)A node that is an element. It converts implicitly to Node.
Node nodestring tagName() @propertyThe tag name, as in the DOM: uppercase for html elements (`"DIV"`), else the local namebool isEmpty() @propertyIs this element empty? No element and no text children (comments don't count), as `:empty`bool hasAttribute(const(char)[] attr)Check if an attribute existsvoid removeAttribute(const(char)[] attr)Remove an attribute from this elementvoid setAttribute(const(char)[] name, const(char)[] value)Set an attribute for this elementstring getAttribute(const(char)[] attr)Get an attribute. It returns `null` if the attribute is missing.const(char)[] getAttributeView(const(char)[] attr)ditto, without copyingElement dup()A deep copy of this element, not attached to the documentElement shallowDup()A copy of this element alone: the tag and the attributes, without childrenvoid copyFrom(Element e)Make this element a copy of another one: the tag, the attributes and the childrenvoid shallowCopyFrom(Element e)Make this element a copy of another one, without the children: the tag and the attributesvoid innerHTML(const(char)[] html) @propertySet the html content of this element (for a `<template>`: its content)string innerText() @propertyThe text of the element (the same as `textContent`: here nothing depends on the layout)void outerHTML(const(char)[] html) @propertyReplace this element with the html (parsed in the context of the parent)bool matches(const(char)[] selector)Does this element match a css selector?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)AttributeA simple key/value struct representing a html attributeAttributeViewditto, as slices of the document memory (see `attributesView`)A range of attributes. It keeps the document alive.
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)) { ... }this(const(char)[] selector)Compile a selector. It throws on invalid syntax.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.
Functions 6
bool isValidSelector(const(char)[] css) @nogc nothrowIs this a valid css selector? It works at compile time too.auto frontOrThrow(T)(T range) if (isInputRange!T)Get the first element of a range or throw an exceptionauto 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 argsauto 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)auto 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.auto 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
DefaultChunkSize = 16 * 1024Default chunk size for Parsing.Lazy
Templates 3
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]";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 htmlCTFE needs compiler memory and time: some tens of KB take about 1 s, a 600 KB page about 1 GB and 10 s (dmd).
The result of a navigation with the filter show: Element for Show.Element, else Node