Skip to content

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.

Reasons to:

  • The tree a browser builds. lxml.html parses 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: no tbody in tables, misnested tags closed differently, viewBox lowercased 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, iterparse and XPath on XML with namespaces. Parsec’s parsec_html.xml parses XML, but it can’t be changed and has no XPath from Python yet.
  • Compiled XPath and extensions. lxml has etree.XPath objects, 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.html extras. Forms (form.fields, submit_form), make_links_absolute, iterlinks and the cleaner in lxml_html_clean have 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.
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
  • Text is nodes, not .text and .tail. lxml keeps the text before an element’s first child in el.text, and the text after the element in el.tail. Parsec keeps text as nodes in the tree, as the DOM does. node.text() is text_content(); for the pieces, walk iter(include_text=True).
  • Strings are plain. lxml’s XPath strings are “smart strings” with getparent(). Parsec’s are str. 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. //svg finds SVG elements; //DIV finds nothing in either.
  • One document, not a root element. lxml.html.fromstring guesses whether you gave it a document or a fragment and hands back an element (sometimes a div it made up to hold several). HTMLParser always gives a document; page.root is <html>, and page.body is the body.
  • Editing is by method on the node. There’s no parent.remove(child); the child takes itself out.
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>"
# Before
import lxml.html
doc = 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.0
doc.xpath("string(//li[@data-sku=$s]/span)", s="B2") # '£31'
# After
from parsec_html import HTMLParser
page = HTMLParser(H)
page.xpath("//li[@class='item']/a/text()") # ['Kettle', 'Toaster']
page.xpath("//li/@data-sku") # ['A1', 'B2']
page.xpath("count(//li)") # 2.0
page.xpath("string(//li[@data-sku=$s]/span)", s="B2") # '£31'
# Before
rows = [(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')]
# After
rows = [(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')]
# 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']
# Before
p = lxml.html.fromstring("<p>Hi <b>there</b> you</p>")
p.text, p.find("b").tail, p.text_content() # ('Hi ', ' you', 'Hi there you')
# After
p = 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')
H = "<div><p>keep</p><span class=ad>ad</span> tail text<p>x</p></div>"
# Before
div = 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>'
# After
page = 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>'
# Before
p = 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>'
# After
p = HTMLParser("<p>Read <b>this</b> now</p>").css_first("p")
p.css_first("b").unwrap()
p.html # '<p>Read this now</p>'
from urllib.parse import urljoin
H = "<p><a href=/a>a</a> <a href=https://x.example/>x</a></p>"
# Before
p = lxml.html.fromstring(H)
p.make_links_absolute("https://shop.example/")
p.xpath("//a/@href") # ['https://shop.example/a', 'https://x.example/']
# After
page = 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.

data = "<p>héllo</p>".encode("utf-8")
# Before
lxml.html.document_fromstring(data).text_content() # 'héllo'
# After
HTMLParser(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.

chunks = [b"<ul><li>a", b"<li>b</u", b"l>"]
# Before
from lxml import etree
parser = etree.HTMLParser()
for c in chunks:
parser.feed(c)
parser.close().xpath("//li/text()") # ['a', 'b']
# After
from parsec_html import StreamParser
s = 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.

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.

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:

# Before
div = 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>'
# After
div = 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>'
  • //table/tr matches 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') is nan in Parsec, as the spec says. Numbers that come back as numbers are the same float.
  • getnext() skips text; next doesn’t. lxml’s siblings are elements only. Parsec’s include text nodes; use xpath("following-sibling::*[1]") for the next element.
  • fromstring vs a document. Code that did lxml.html.fromstring(page).xpath("//title") works with HTMLParser(page).xpath("//title"). Code that relied on fromstring returning the single element of a fragment wants HTMLParser(html, is_fragment=True).root.
  • Insert copies. insert_child(node) inserts a copy; pass move=True to move a node, as append does in lxml.

Your XPath doesn’t need rewriting, so the test is simple: run each query you use through both, on pages you already scrape.

# Both
QUERIES = ["//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.