Moving from lxml
If you scrape HTML with lxml.html and XPath, your queries can come with you unchanged: Parsec’s xpath() gives back what lxml’s gives back, a list of elements and strings, a float, a bool or a str. What changes is the tree the queries run on, which is the one the HTML Standard builds, and the calls you make on an element once you have it.
Every example runs as written: the lxml half against lxml 6.2.1 (libxml2 2.14.6) with cssselect 1.6.0, the Parsec half against parsec-web 0.3.1, on CPython 3.14.
Should you move?
Section titled “Should you move?”Reasons to:
- The tree a browser builds.
lxml.htmlparses with libxml2’s HTML parser, which predates the HTML Standard’s parsing rules. On well-formed pages it rarely matters. On the rest, lxml and a browser disagree: notbodyin tables, misnested tags closed differently,viewBoxlowercased in SVG. Parsec builds what a browser builds, so an XPath you worked out in the browser’s inspector finds the same nodes. Tree shapes has examples. - Bytes decoded as a browser decodes them. lxml reads undeclared UTF-8 bytes as Latin-1 and gives you
héllo. Parsec reads them as UTF-8, and follows the HTML Standard’s sniffing for everything else. - CSS selectors built in, run in Rust, without cssselect translating them to XPath.
- Threads. A parsed page can be queried from many threads at once, and the GIL is let go while it parses and queries; on free-threaded Python 3.14t there’s no GIL at all.
- Speed. We haven’t published a benchmark against lxml, so there’s no figure here. Checking your pages shows how to time both on pages you scrape.
Reasons to stay, or to keep lxml for some jobs:
- XML. lxml is a complete XML toolkit: XSLT, XML Schema, RelaxNG,
iterparseand XPath on XML with namespaces. Parsec’sparsec_html.xmlparses XML, but it can’t be changed and has no XPath from Python yet. - Compiled XPath and extensions. lxml has
etree.XPathobjects, EXSLT (regular expressions in queries) and Python extension functions. Parsec compiles each query when you call it, and has XPath 1.0’s function library only. lxml.htmlextras. Forms (form.fields,submit_form),make_links_absolute,iterlinksand the cleaner inlxml_html_cleanhave no Parsec equivalents.- Number formatting in XPath. If your output depends on how
string(1 div 3)prints, Parsec follows the XPath spec where libxml2 rounds to 15 digits. See the table in Python: XPath.
What maps to what
Section titled “What maps to what”| lxml 6.2 | Parsec |
|---|---|
lxml.html.document_fromstring(html) |
HTMLParser(html) |
lxml.html.fromstring(html) |
HTMLParser(html), then .body or a selector |
lxml.html.fragment_fromstring(html, create_parent="div") |
HTMLParser(html, is_fragment=True) |
etree.HTMLParser(encoding=...) |
HTMLParser(data, transport_encoding=...) |
parser.feed(...), parser.close() |
StreamParser().feed(...), .close() |
el.xpath(query, var=value) |
node.xpath(query, var=value) |
etree.XPath(query) |
not yet; call xpath() |
el.cssselect("a") |
node.css("a") |
el.find(".//a"), el.findall(...) |
node.css_first("a"), node.css("a"), or xpath() |
el.tag |
node.tag |
el.get("href"), el.attrib |
node.attrs.get("href"), node.attributes |
el.set("rel", "x"), del el.attrib["x"] |
node.attrs["rel"] = "x", del node.attrs["x"] |
el.text, el.tail |
text nodes: node.first_child, node.next |
el.text_content() |
node.text() |
el.getparent(), getnext(), getprevious() |
node.parent, node.next, node.prev (text nodes included) |
el.iterchildren(), list(el) |
node.iter() |
el.iter("a"), el.iterdescendants() |
node.css("a"), node.traverse() |
el.drop_tree() |
node.decompose() |
el.drop_tag() |
node.unwrap() |
parent.remove(el) |
node.decompose(), but see remove drops the tail |
el.append(child), addnext, addprevious |
node.insert_child(child, move=True), insert_after, insert_before |
etree.tostring(el, encoding=str) |
node.html |
el.sourceline |
node.position[0], with positions=True |
make_links_absolute(base) |
urllib.parse.urljoin over xpath("//@href")’s owners; see below |
API differences
Section titled “API differences”- Text is nodes, not
.textand.tail. lxml keeps the text before an element’s first child inel.text, and the text after the element inel.tail. Parsec keeps text as nodes in the tree, as the DOM does.node.text()istext_content(); for the pieces, walkiter(include_text=True). - Strings are plain. lxml’s XPath strings are “smart strings” with
getparent(). Parsec’s arestr. To get from an attribute back to its element, select the element://a[@href]rather than//a/@href. - No namespaces argument. HTML names have no prefixes, and Parsec matches as lxml does in HTML: lowercase, in no namespace.
//svgfinds SVG elements;//DIVfinds nothing in either. - One document, not a root element.
lxml.html.fromstringguesses whether you gave it a document or a fragment and hands back an element (sometimes adivit made up to hold several).HTMLParseralways gives a document;page.rootis<html>, andpage.bodyis the body. - Editing is by method on the node. There’s no
parent.remove(child); the child takes itself out.
Side by side
Section titled “Side by side”XPath on a listing
Section titled “XPath on a listing”H = "<title>Shop</title><ul><li class=item data-sku=A1><a href=/a>Kettle</a> <span class=price>£24</span><li class=item data-sku=B2><a href=/b>Toaster</a> <span class=price>£31</span></ul>"
# Beforeimport lxml.htmldoc = lxml.html.document_fromstring(H)doc.xpath("//li[@class='item']/a/text()") # ['Kettle', 'Toaster']doc.xpath("//li/@data-sku") # ['A1', 'B2']doc.xpath("count(//li)") # 2.0doc.xpath("string(//li[@data-sku=$s]/span)", s="B2") # '£31'# Afterfrom parsec_html import HTMLParserpage = HTMLParser(H)page.xpath("//li[@class='item']/a/text()") # ['Kettle', 'Toaster']page.xpath("//li/@data-sku") # ['A1', 'B2']page.xpath("count(//li)") # 2.0page.xpath("string(//li[@data-sku=$s]/span)", s="B2") # '£31'XPath from an element
Section titled “XPath from an element”# Beforerows = [(li.get("data-sku"), li.xpath("string(a)"), li.xpath("string(span)")) for li in doc.xpath("//li")]rows # [('A1', 'Kettle', '£24'), ('B2', 'Toaster', '£31')]# Afterrows = [(li.attrs.get("data-sku"), li.xpath("string(a)"), li.xpath("string(span)")) for li in page.xpath("//li")]rows # [('A1', 'Kettle', '£24'), ('B2', 'Toaster', '£31')]CSS selectors
Section titled “CSS selectors”# Before[a.text_content() for a in doc.cssselect("li.item > a")] # ['Kettle', 'Toaster']# After[a.text() for a in page.css("li.item > a")] # ['Kettle', 'Toaster']Text, .text and .tail
Section titled “Text, .text and .tail”# Beforep = lxml.html.fromstring("<p>Hi <b>there</b> you</p>")p.text, p.find("b").tail, p.text_content() # ('Hi ', ' you', 'Hi there you')# Afterp = HTMLParser("<p>Hi <b>there</b> you</p>").css_first("p")b = p.css_first("b")p.first_child.text_content, b.next.text_content, p.text() # ('Hi ', ' you', 'Hi there you')Remove elements
Section titled “Remove elements”H = "<div><p>keep</p><span class=ad>ad</span> tail text<p>x</p></div>"
# Beforediv = lxml.html.fromstring(H)for ad in div.cssselect(".ad"): ad.drop_tree()lxml.html.tostring(div, encoding=str) # '<div><p>keep</p> tail text<p>x</p></div>'# Afterpage = HTMLParser(H)for ad in page.css(".ad"): ad.decompose()page.css_first("div").html # '<div><p>keep</p> tail text<p>x</p></div>'Remove a tag, keep what’s in it
Section titled “Remove a tag, keep what’s in it”# Beforep = lxml.html.fromstring("<p>Read <b>this</b> now</p>")p.find("b").drop_tag()lxml.html.tostring(p, encoding=str) # '<p>Read this now</p>'# Afterp = HTMLParser("<p>Read <b>this</b> now</p>").css_first("p")p.css_first("b").unwrap()p.html # '<p>Read this now</p>'Change attributes, make links absolute
Section titled “Change attributes, make links absolute”from urllib.parse import urljoinH = "<p><a href=/a>a</a> <a href=https://x.example/>x</a></p>"
# Beforep = lxml.html.fromstring(H)p.make_links_absolute("https://shop.example/")p.xpath("//a/@href") # ['https://shop.example/a', 'https://x.example/']# Afterpage = HTMLParser(H)for a in page.css("a[href]"): a.attrs["href"] = urljoin("https://shop.example/", a.attrs["href"])page.xpath("//a/@href") # ['https://shop.example/a', 'https://x.example/']make_links_absolute also rewrites src, action, CSS url()s and more. If you depend on those, extend the selector to [href], [src] and so on.
Bytes with no declared encoding
Section titled “Bytes with no declared encoding”data = "<p>héllo</p>".encode("utf-8")
# Beforelxml.html.document_fromstring(data).text_content() # 'héllo'# AfterHTMLParser(data).text() # 'héllo'lxml falls back to Latin-1 when nothing declares an encoding. Parsec treats valid UTF-8 as UTF-8, as browsers do, and uses windows-1252 for the rest. Pass the HTTP charset as transport_encoding when you have it.
Parse in pieces
Section titled “Parse in pieces”chunks = [b"<ul><li>a", b"<li>b</u", b"l>"]
# Beforefrom lxml import etreeparser = etree.HTMLParser()for c in chunks: parser.feed(c)parser.close().xpath("//li/text()") # ['a', 'b']# Afterfrom parsec_html import StreamParsers = StreamParser()for c in chunks: s.feed(c)s.close().xpath("//li/text()") # ['a', 'b']close() gives the parsed page, as lxml’s gives its root.
Tree shapes
Section titled “Tree shapes”The same input, through lxml.html.document_fromstring and through Parsec:
| Input | lxml 6.2.1 | Parsec, and browsers |
|---|---|---|
<table><tr><td>1</table> |
table/tr/td |
table/tbody/tr/td |
<p>a<div>b</div>c</p> |
<p>a</p><div>b</div>c |
<p>a</p><div>b</div>c<p></p> |
<b>1<i>2</b>3</i> |
<b>1<i>2</i></b>3 |
<b>1<i>2</i></b><i>3</i> |
<svg viewBox="0 0 1 1"><foreignObject/> |
viewbox, foreignobject |
viewBox, foreignObject |
<template><p>t</p></template> |
the p is a child |
the p is in the template’s contents, not the tree |
The first is the one that breaks queries: //table/tr finds nothing in Parsec. Write //table//tr, or //tbody/tr. You’ll see the same tbody in the browser’s inspector, so XPath copied from there works in Parsec as it is.
Gotchas
Section titled “Gotchas”remove drops the tail
Section titled “remove drops the tail”In lxml, parent.remove(el) takes the element’s tail text with it, and drop_tree() keeps it. Parsec has no tail: text after an element is its own node, and decompose() leaves it where it is, as drop_tree() does. If you relied on remove() taking the tail, take the text node out too:
# Beforediv = lxml.html.fromstring("<div><span>ad</span> tail<p>x</p></div>")div.remove(div.find("span"))lxml.html.tostring(div, encoding=str) # '<div><p>x</p></div>'# Afterdiv = HTMLParser("<div><span>ad</span> tail<p>x</p></div>").css_first("div")span = div.css_first("span")if span.next is not None and span.next.is_text_node: span.next.decompose()span.decompose()div.html # '<div><p>x</p></div>'And the rest
Section titled “And the rest”//table/trmatches nothing: see Tree shapes.- Numbers turned into strings follow XPath 1.0 in Parsec and libxml2’s 15-digit rounding in lxml:
string(0.1 + 0.2)is'0.30000000000000004'in Parsec and'0.3'in lxml.number('1e3')isnanin Parsec, as the spec says. Numbers that come back as numbers are the samefloat. getnext()skips text;nextdoesn’t. lxml’s siblings are elements only. Parsec’s include text nodes; usexpath("following-sibling::*[1]")for the next element.fromstringvs a document. Code that didlxml.html.fromstring(page).xpath("//title")works withHTMLParser(page).xpath("//title"). Code that relied onfromstringreturning the single element of a fragment wantsHTMLParser(html, is_fragment=True).root.- Insert copies.
insert_child(node)inserts a copy; passmove=Trueto move a node, asappenddoes in lxml.
Checking your pages
Section titled “Checking your pages”Your XPath doesn’t need rewriting, so the test is simple: run each query you use through both, on pages you already scrape.
# BothQUERIES = ["//a/@href", "//title/text()", "count(//li)", "string(//h1)"]
def differences(html): old = lxml.html.document_fromstring(html) new = HTMLParser(html) out = {} for q in QUERIES: a, b = old.xpath(q), new.xpath(q) a = [x if isinstance(x, str) else x.tag for x in a] if isinstance(a, list) else a b = [x if isinstance(x, str) else x.tag for x in b] if isinstance(b, list) else b if a != b: out[q] = (a, b) return out
differences("<title>T</title><h1>Hi</h1><ul><li><a href=/x>x</a></ul>") # {}Where a query differs, it’s usually a tree shape: look at the page in a browser’s inspector, and you’ll see Parsec’s tree. Then time both with timeit on the same pages, since no published figure stands in for yours.