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-safe by design. Every method accepts 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.

Python: two packages, one API. 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.
LanguagePackageSource

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&amp;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&amp;6, has value: True)
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);
KindSupported
Simpletype, *, #id, .class
Attributes[a], =, ~=, |=, ^=, $=, *=, with the i / s flags
Combinatorsdescendant, >, +, ~, 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:

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.

Availability. Forms and 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.

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 (&amp; → &); 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&amp;A &copy; 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:

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

MemberWhat 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 / IsFirst match / all matches / check one tag, by HtmlTag, name or TagQuery
Css / CssFirst / IsCssCSS selectors; CssQuery.Compile for reuse
XPath / XPathFirstXPath to tags; XPathQuery.Compile for reuse
XPathValues / XPathValueXPath to strings: attributes, text, numbers
Text() / TextLineBreaks()Visible text, collapsed or with line structure
Body() / FullSource()Inner / outer HTML as written
AttributeByName / AttributeBodyDecoded value / value as written
Attributes() newAll attributes, lower-case names, decoded values
AttributeHref / AttributeSrcAbsolute URLs
Parent / ChildrenUp (optionally to a matching ancestor) / direct children
NextSibling / PreviousSibling / NextSiblings and the next matching tag in document order
Form() / Forms() newHtmlForm: Action, Method, Enctype, Controls(), Fields(submitter)
HtmlText.Decode / ToTextEntities and text for raw HTML strings
Name, Depth, Start, EndTag name, nesting depth, position in the source

Coming from other parsers

You wroteWith 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.DeEntitizetag.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.TextContenttag.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

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.