Documentation
z3l.FastHtmlParser is a fast, low-allocation HTML / XML parser for scraping and data extraction.
This guide uses C#; every port has the same API in the naming of its language (Css → css,
XPathValues → xpath_values), see other languages.
Want to see it first? Parse a page in the browser.
Install
.NET 9 or .NET 10, no dependencies. Trimming and Native AOT compatible.
dotnet add package z3l.FastHtmlParser
Quick start
using z3l.FastHtmlParser;
var doc = new HtmlParser(html, "https://example.com/catalog/");
// first match
var title = doc.Find(HtmlTag.H1).Text();
var price = doc.Find(HtmlTag.Span, cls: "price").Text();
// chains never throw: a missing tag gives null at the end
var phone = doc.Find(HtmlTag.Div, id: "contacts")
.Find(HtmlTag.A, cls: "phone")
.AttributeHrefTelephone();
// all matches; links are made absolute against the page URL
foreach (var a in doc.Find(HtmlTag.Div, cls: "gallery").FindAll(HtmlTag.A))
Console.WriteLine(a.AttributeHref());
// or CSS selectors / XPath 1.0
var cards = doc.Css("div.card:has(span.price) > a");
var links = doc.XPathValues("//div[@class='gallery']//a/@href");
null and returns null or an empty
list, so a chain over a page that changed gives null at the end instead of a NullReferenceException
in the middle.Other languages
The same parser, ported by hand to each language and checked against the same conformance data as the .NET original. Pick a language: the install command and the first steps.
pip install fasthtmlparser is a wrapper over the Rust port: the fastest,
with wheels for Linux, Windows and macOS. pip install fasthtmlparser-pure is a pure-Python port with no compiled code, for PyPy and
places where binary wheels can't be installed. The calls and the results are the same; only the import differs:
import fasthtmlparser as fh or import fasthtmlparser_pure as fh.| Language | Package | Source |
|---|
Finding tags
Find returns the first match, FindAll all matches (lazily), Is checks one tag. They work on the
whole document or inside a tag: tag.Find(...) searches its descendants.
doc.Find(HtmlTag.Table);
doc.Find(HtmlTag.Li, cls: "item"); // one of the space-separated classes
doc.Find(HtmlTag.Div, id: "main");
doc.Find(HtmlTag.Dt, text: "Price"); // visible text: tags removed, entities decoded
doc.Find("custom-element"); // names that are not in HtmlTag
// any combination of criteria
doc.Find(new TagQuery(HtmlTag.Meta) { Attribute = HtmlAttribute.Property, AttributeValue = "og:title" });
doc.FindAll(new TagQuery(HtmlTag.Img) { AttributeName = "data-lazy", AttributeValue = "true" });
doc.Find(new TagQuery { IdStartsWith = "product-" }); // any tag
tag.Is(new TagQuery(HtmlTag.Li) { Class = "item", TextStartsWith = "Price" });
TagQuery criteria: Class, Id, IdStartsWith, Attribute / AttributeName +
AttributeValue, Text, TextStartsWith, Body, BodyStartsWith, Source.
Null criteria are not checked. A query is a struct: searching allocates nothing, and the name is compared first with one integer comparison.
HtmlTag and HtmlAttribute hold about 250 values each (HTML, SVG, MathML, RSS, Atom, sitemaps). Any other name works as a string.
Shortcuts: a method for every search
using z3l.FastHtmlParser.Shortcuts;
doc.FindByNameClass(HtmlTag.Span, "price");
doc.FindByNameText(HtmlTag.Dt, "Price").NextSiblingByName(HtmlTag.Dd).Text();
doc.FindAllByNameAttribute(HtmlTag.Img, HtmlAttribute.DataSrc, "...");
doc.FindByNameItemprop(HtmlTag.Span, "price");
tag.IsNameClass(HtmlTag.Div, "card");
tag.ParentByName(HtmlTag.Table);
tag.AttributeTitle();
Every shortcut is a one-line call of the core API; they live in their own namespace, so the core API stays small unless you import them.
Reading a tag
tag.Name; // "div"
tag.Text(); // visible text, entities decoded, whitespace collapsed
tag.TextLineBreaks(); // text with line breaks: <br>, block elements → new line, <p> → paragraph
tag.Body(); // inner HTML
tag.FullSource(); // outer HTML
tag.AttributeHref(); // absolute URL
tag.AttributeByName(HtmlAttribute.Content); // decoded value
tag.AttributeBody(HtmlAttribute.Content); // value as written in the source
foreach (var (name, value) in tag.Attributes()) { } // all attributes
tag.Attributes() new
All attributes of a tag in source order, as a browser reads them: names in lower case, values decoded, a repeated name kept
once (the first). Each TagAttribute has Name, Value, Body (the value as written) and
HasValue, and deconstructs into (name, value). Known names take no allocation.
// <input type=checkbox name="agree" checked data-id="5&6">
foreach (var a in input.Attributes())
Console.WriteLine($"{a.Name} = {a.Value} (written as {a.Body}, has value: {a.HasValue})");
// type = checkbox (written as checkbox, has value: True)
// name = agree ...
// checked = (written as , has value: False)
// data-id = 5&6 (written as 5&6, has value: True)
Navigation
tag.Parent();
tag.Parent(HtmlTag.Table); // nearest enclosing <table>
tag.Parent(new TagQuery(HtmlTag.Div) { Class = "card" });
tag.Children(); // direct children
foreach (var descendant in tag) { } // all tags inside
tag.NextSibling();
tag.NextSibling(HtmlTag.Dd); // <dt>Price</dt><dd>100</dd>
tag.PreviousSibling();
tag.Next(HtmlTag.Div); // first <div> after this tag
var price = doc.Find(HtmlTag.Dt, text: "Price").NextSibling(HtmlTag.Dd).Text();
Wherever a TagQuery is expected, a plain HtmlTag or a tag name works too: it means "a tag with this name".
Parent() is O(1): the parent is recorded while parsing.
XPath 1.0
XPath works on the document or inside a tag. XPath returns tags, XPathValues / XPathValue return
values: decoded attributes, text(), the visible text of tags, or the result of count(), sum(), string()...
doc.XPath("//div[@class='card']//span[@class='price']");
doc.XPathFirst("//ul[@id='menu']/li[last()]/a");
doc.XPathValues("//a[contains(@href, '/product/')]/@href");
doc.XPathValue("//dt[.='Price']/following-sibling::dd[1]");
doc.XPathValue("count(//table//tr)"); // "12"
var card = doc.XPathFirst("//div[@id='main']");
card.XPath(".//a"); // relative paths start at the tag
card.XPath("//a"); // '/' and '//' search the whole document
// compile once, reuse on any number of pages and threads
static readonly XPathQuery Titles = XPathQuery.Compile("//article//h3/a/@title");
page.XPathValues(Titles);
All axes (except namespace), predicates, |, operators and the XPath 1.0 functions are supported, plus
ends-with(), lower-case() and upper-case(). HTML rules apply: names are case-insensitive, entities are decoded,
and the string-value of an element is its Text(). //name and [@attr='value'] run as a linear scan of the
tag list. String expressions are compiled once and cached; an invalid expression throws ArgumentException with the position of the error.
CSS selectors
Css, CssFirst and IsCss work as querySelectorAll, querySelector and matches in a browser.
doc.Css("article.product_pod h3 > a");
doc.CssFirst("ul#menu > li:last-child a")?.AttributeHref();
doc.Css("table tr:nth-child(odd) > td:nth-child(2)");
doc.Css("div.quote:has(a.tag[href*=love]) span.text");
doc.Css("a[href$='.pdf' i]:not([rel~=nofollow])");
doc.Css("h2:contains('Price') + p"); // the visible text contains the string
var list = doc.CssFirst("ul.menu");
list.Css("> li"); // its children
list.Css(":scope > li > a");
link.IsCss("nav a.active");
// compile once, reuse on any number of pages and threads
static readonly CssQuery Prices = CssQuery.Compile("div.card span.price");
page.Css(Prices);
| Kind | Supported |
|---|---|
| Simple | type, *, #id, .class |
| Attributes | [a], =, ~=, |=, ^=, $=, *=, with the i / s flags |
| Combinators | descendant, >, +, ~, selector lists |
| Structural | :first-child, :last-child, :only-child, the -of-type variants, :nth-child(An+B [of S]), :nth-last-child(), :nth-of-type(), :nth-last-of-type(), :empty, :root, :scope |
| Logical | :not(), :is(), :where(), :has() |
| Forms, links | :link, :checked, :disabled, :enabled, :required, :optional |
| Non-standard | :contains('text'): the visible text contains the string |
Ids, classes and attribute values are case-sensitive as in a standards-mode page, except the values HTML compares ignoring case
(type, rel, lang...). Results are cross-checked against AngleSharp. A simple selector runs as fast as
FindAll; tag.Css("div a") matches the whole selector against the document, as in a browser, and returns the tags inside tag.
Forms new
Form() gives the form of a tag (the <form> itself or the form a control belongs to), Forms() all forms of the page.
Fields() returns what a browser sends when the form is submitted, ready for FormUrlEncodedContent.
var form = doc.Find(HtmlTag.Form, id: "form1").Form();
form.Action; // absolute URL
form.Method; // "get" / "post"
form.Enctype; // "application/x-www-form-urlencoded", "multipart/form-data", "text/plain"
form.Controls(); // the input, select, textarea, button... tags of the form
form.Fields(); // [("__VIEWSTATE", "..."), ("__EVENTVALIDATION", "..."), ("txtSearch", "phone")]
// an ASP.NET postback: send the clicked button too
var button = doc.Find(new TagQuery(HtmlTag.Input) { AttributeName = "name", AttributeValue = "btnSearch" });
var content = new FormUrlEncodedContent(form.Fields(button));
var response = await http.PostAsync(form.Action, content);
// change a field before sending
var fields = form.Fields(button).Select(f => f.Key == "txtSearch" ? new(f.Key, "laptop") : f);
As in a browser:
- controls without a name and disabled ones (also inside
<fieldset disabled>) are left out; - a checkbox or radio button is sent only when checked, with its value or
on; - a
selectsends its selected option or the first enabled one;multiplesends every selected option; an option withoutvaluesends its text; - a
textareasends its text; controls outside the form withform="id"belong to it; - submit buttons are sent only as the submitter; file inputs are left out.
Cross-checked with AngleSharp's form submission. Where AngleSharp differs from the HTML standard (value sanitization,
form="id" outside the form, CR LF in every value) the standard is followed. See it on a real form.
Attributes() are in the next release of the .NET package
(see the changelog); the ports follow.Tables
There is no table object: rows and cells are two selectors away, and :scope keeps nested tables out.
var table = doc.CssFirst("table#prices");
var header = table.Css(":scope > thead > tr > th").Select(th => th.Text()).ToArray();
foreach (var row in table.Css(":scope > tr, :scope > tbody > tr"))
{
var cells = row.Css(":scope > td").Select(td => td.Text()).ToArray();
if (cells.Length == 0) continue; // a header row inside tbody
Console.WriteLine(string.Join(" | ", cells));
}
// a "key: value" table
var specs = doc.Css("table.specs tr")
.ToDictionary(tr => tr.Find(HtmlTag.Th).Text() ?? "", tr => tr.Find(HtmlTag.Td).Text());
The parser does not insert the implicit <tbody> a browser adds, so :scope > tr finds rows written right inside
<table>. A new <tr> or <td> ends an open one, as in HTML5.
See tables on a real page.
Links and URLs
Pass the page URL to the constructor and links come back absolute, resolved against it as a browser does:
var doc = new HtmlParser(html, "https://example.com/catalog/page-2.html");
doc.Find(HtmlTag.A).AttributeHref(); // "https://example.com/catalog/item-5.html"
doc.Find(HtmlTag.Img).AttributeSrc(); // absolute image URL
doc.Find(HtmlTag.A, cls: "phone").AttributeHrefTelephone(); // the number of a tel: link
tag.AttributeHref("https://other.example/"); // resolve against another URL
Values are decoded (& → &); percent-escapes are kept as written.
Parsing from a buffer
Text that is already in a char[] or a pooled buffer can be parsed in place, without copying it into a string.
var doc = HtmlParser.Parse(chars.AsMemory(0, length), url); // the buffer must not change while doc is used
// hand a pooled buffer over: Dispose returns it to the pool
var owner = MemoryPool<char>.Shared.Rent(maxChars);
int length = reader.Read(owner.Memory.Span);
using var page = HtmlParser.Parse(owner, length, url);
Everything works as with a string; PageSource makes the string on its first use. A document does not have to be disposed;
Dispose() only releases the text and the tag list early.
Text helpers for raw HTML
HtmlText.Decode("Q&A © 2026"); // "Q&A © 2026"
HtmlText.ToText("<b>Hello</b> world"); // "Hello world"
HtmlText.ToTextWithLineBreaks("<p>One</p><p>Two</p>");
Parsing rules
The parser builds a flat list of tags, not a full DOM, and follows the HTML rules that matter for scraping:
<!-- comments -->are singleHtmlTag.Commenttags; markup inside them is ignored.- The content of
script,style,textarea,title,iframe,xmp,noembed,noframesis text, not markup. - Void elements (
img,br,meta,link,input,hr...) and<!doctype>never contain other tags. Text()returns the visible text: comments and the content ofscript,style,noscript,templateare skipped.- Optional end tags work as in HTML5: a new
<li>ends an open<li>,<td>/<tr>end open cells and rows,<dt>/<dd>and<option>end their open siblings, a block element ends an open<p>. - Tags left open are ended by the end tag of an enclosing element or by the end of the document, so a truncated page keeps its text.
<starts a tag only before a letter,/,!or?: ina < bit is text.- Quoted attribute values may contain
<,>and text that looks like another attribute: in<a title="see id=5" id="real">the id isreal. - A document that starts with
<?xml(RSS, Atom, sitemap, XHTML) is parsed by XML rules: an element is closed only by its end tag or/>, so an RSS<link>keeps its content. - Attribute values are returned decoded, as a browser reads them;
AttributeBodyreturns the value as written. CR LF reads as LF. - Nesting deeper than 512 levels is flattened, as in browsers.
- Parsing time grows linearly with the size of the page on any markup, including thousands of unclosed tags and stray end tags.
On the test pages and on a set of broken-markup snippets the parser finds the same elements, texts, attribute values and parents as AngleSharp,
apart from the trees a browser builds implicitly (an inserted <tbody>, an ignored second <body>).
A parsed document is read-only and thread-safe.
API at a glance
| Member | What it does |
|---|---|
new HtmlParser(html, url) | Parses a string; url resolves relative links |
HtmlParser.Parse(memory, url) | Parses a ReadOnlyMemory<char> in place; an IMemoryOwner<char> overload takes a pooled buffer |
Find / FindAll / Is | First match / all matches / check one tag, by HtmlTag, name or TagQuery |
Css / CssFirst / IsCss | CSS selectors; CssQuery.Compile for reuse |
XPath / XPathFirst | XPath to tags; XPathQuery.Compile for reuse |
XPathValues / XPathValue | XPath to strings: attributes, text, numbers |
Text() / TextLineBreaks() | Visible text, collapsed or with line structure |
Body() / FullSource() | Inner / outer HTML as written |
AttributeByName / AttributeBody | Decoded value / value as written |
Attributes() new | All attributes, lower-case names, decoded values |
AttributeHref / AttributeSrc | Absolute URLs |
Parent / Children | Up (optionally to a matching ancestor) / direct children |
NextSibling / PreviousSibling / Next | Siblings and the next matching tag in document order |
Form() / Forms() new | HtmlForm: Action, Method, Enctype, Controls(), Fields(submitter) |
HtmlText.Decode / ToText | Entities and text for raw HTML strings |
Name, Depth, Start, End | Tag name, nesting depth, position in the source |
Coming from other parsers
| You wrote | With FastHtmlParser |
|---|---|
new HtmlDocument(); doc.LoadHtml(html) (HtmlAgilityPack) | new HtmlParser(html, url) |
doc.DocumentNode.SelectNodes("//a") | doc.XPath("//a") (empty list, never null) |
node.InnerText / HtmlEntity.DeEntitize | tag.Text() (decoded, visible text only) |
node.GetAttributeValue("href", "") | tag.AttributeHref() (absolute) or AttributeByName("href") |
parser.ParseDocument(html) (AngleSharp) | new HtmlParser(html, url) |
doc.QuerySelectorAll("div > a") | doc.Css("div > a") |
el.TextContent | tag.Text() (scripts and styles left out) |
soup.select("a") / soup.find("div", class_="x") (BeautifulSoup) | doc.css("a") / doc.find("div", class_="x") in Python |
$("a").attr("href") (cheerio) | doc.cssFirst("a")?.attr("href") in JavaScript |
Performance tips
- Compile what you reuse.
XPathQuery.CompileandCssQuery.Compilein astatic readonlyfield skip the cache lookup. - Prefer typed queries in hot loops.
Find(HtmlTag.Span, cls: "price")compares an integer and a span; it allocates nothing. - Search inside a tag.
card.Find(...)scans only the tags inside the card. - Read what you need. Text and attributes are decoded on access; a tag you skip costs nothing.
- Pool the buffers for high-volume crawlers:
HtmlParser.Parse(owner, length, url)withMemoryPool<char>. - Share documents across threads. A parsed document is read-only.
License
Free for individuals and organizations with annual revenue below USD 1,000,000 and fewer than 100 employees, including commercial use. Larger organizations need a commercial license: a one-time payment of USD 1,000 per organization, perpetual, all versions, all ports and every z3l library. See the EULA and pricing.