Moving from selectolax
Parsec’s Python package copies selectolax’s API on purpose, so most scrapers move by changing one import. This page is for the rest of the move: what isn’t there yet, the handful of calls that behave differently, and how to prove on your own pages that nothing changed.
Every example runs as written, the selectolax half against selectolax 1.0.2 and the Parsec half against parsec-web 0.3.1, on CPython 3.14.
Should you move?
Section titled “Should you move?”selectolax’s fast parser is Lexbor, so the honest comparison is Parsec against Lexbor, and then the cost of the Python layer on top.
From Python, on the 13 real pages the benchmarks use (24 MB of Wikipedia, MDN, GitHub, the BBC and others), on an Apple M2 Max with selectolax 1.0.2 (Python speed):
| parsec_html | selectolax | Parsec vs selectolax | |
|---|---|---|---|
| Parse all 13 pages | 66.8 ms | 105.6 ms | 1.6× |
| 32 selectors over all 13 pages | 283.1 ms | 781.4 ms | 2.8× |
Every link’s href and text |
42.6 ms | 50.0 ms | 1.1 to 1.2× |
Underneath, in Rust and C with no Python in the way, the run of 29 November 2026 has Parsec parsing those pages at 362 MB/s to Lexbor 3.0.1’s 242, and running the same 32 selectors in 243 ms to Lexbor’s 715 (parsec.tools/benchmarks).
What else you get:
- One page, many threads. selectolax’s Lexbor parsers aren’t thread-safe, so it’s one parser per thread. A Parsec page can be read by any number of threads at once, and the GIL is let go while it parses and queries. On free-threaded Python (3.14t) it runs with the GIL off.
- Selectors selectolax refuses.
:lang(),:dir(),:valid,:in-rangeand:scoperaise “Can’t parse CSS selector” in selectolax 1.0.2 and match in Parsec. - XPath 1.0 on the same tree, answering the way lxml does.
- Bytes in any encoding, sniffed the way a browser sniffs them, and parse errors and source positions if you ask.
And what selectolax still does better:
- It has more API.
clone(),raw_html,raw_value,html_pretty,select()and its filters,scripts_contain,script_srcs_contain,template_fragments,text_lexbor, the:lexbor-contains()pseudo-class, andcreate_tag()at module level aren’t in Parsec yet. If your code leans on one of these, wait, or ask for it. - Memory, on some pages. Lexbor held less memory than Parsec on 4 of the 13 pages in the same run.
- It’s been around longer. selectolax has years of other people’s scrapers behind it. Parsec’s Python package is months old.
The import
Section titled “The import”# Beforefrom selectolax.lexbor import LexborHTMLParser
page = LexborHTMLParser("<ul><li class=a>one<li>two</ul>")[li.text() for li in page.css("li")] # ['one', 'two']# Afterfrom parsec_html import HTMLParser
page = HTMLParser("<ul><li class=a>one<li>two</ul>")[li.text() for li in page.css("li")] # ['one', 'two']Still on from selectolax.parser import HTMLParser? That’s the old Modest backend. selectolax 1.0 deprecated it and points you at the Lexbor one, and Parsec’s tree is Lexbor’s tree, not Modest’s, so expect output to change where Modest got the HTML Standard wrong. Diff a sample first; Checking your pages shows how.
What maps to what
Section titled “What maps to what”Everything else on LexborHTMLParser and LexborNode that Parsec has works under the same name. These are the differences:
| selectolax 1.0.2 | parsec_html 0.3.1 |
|---|---|
LexborHTMLParser, LexborNode, LexborAttributes |
HTMLParser, Node, Attributes |
SelectolaxError for a bad selector |
SelectorError, a ValueError |
<a href>’s attributes is {'href': None} |
{'href': ''} |
decompose() frees the node |
it reads as empty after, and so does everything that was in it |
remove() is decompose() |
takes the node out but keeps it, to put back with move=True |
root.decompose() raises |
decomposes <html>; only the document node itself raises |
attrs.items(), keys(), values() are iterators |
lists |
iter(), traverse() are generators |
iterators over a list taken when you call them |
bytes are UTF-8, or sniffed with encoding=True |
always sniffed as a browser sniffs them |
| no XPath | xpath() on the parser and on every node |
clone(), raw_html, html_pretty, select(), scripts_contain, :lexbor-contains() |
not yet |
Python keeps the full list, with every member of HTMLParser and Node.
Side by side
Section titled “Side by side”Each task once with selectolax, once with Parsec.
Read a listing
Section titled “Read a listing”H = "<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>"
# Beforefrom selectolax.lexbor import LexborHTMLParserpage = LexborHTMLParser(H)rows = [(li.attrs["data-sku"], li.css_first("a").text(), li.css_first(".price").text()) for li in page.css("li.item")]rows # [('A1', 'Kettle', '£24'), ('B2', 'Toaster', '£31')]# Afterfrom parsec_html import HTMLParserpage = HTMLParser(H)rows = [(li.attrs["data-sku"], li.css_first("a").text(), li.css_first(".price").text()) for li in page.css("li.item")]rows # [('A1', 'Kettle', '£24'), ('B2', 'Toaster', '£31')]Not a character changed but the import.
Clean a page before taking its text
Section titled “Clean a page before taking its text”H = "<article><p>Read <b>this</b>.</p><script>track()</script><div class=ad>Buy!</div></article>"
# Beforepage = LexborHTMLParser(H)page.strip_tags(["script"])for ad in page.css(".ad"): ad.decompose()page.unwrap_tags(["b"])page.css_first("article").html # '<article><p>Read this.</p></article>'# Afterpage = HTMLParser(H)page.strip_tags(["script", ".ad"])page.unwrap_tags(["b"])page.css_first("article").html # '<article><p>Read this.</p></article>'The selectolax code runs unchanged on Parsec too. The difference is the shortcut: selectolax’s strip_tags takes tag names and quietly passes over .ad, where Parsec’s takes any selector, as both libraries’ unwrap_tags already do.
A selector that doesn’t parse
Section titled “A selector that doesn’t parse”# Beforefrom selectolax.lexbor import SelectolaxErrortry: LexborHTMLParser("<p>").css("p[")except SelectolaxError: failed = Truefailed # True# Afterfrom parsec_html import SelectorErrortry: HTMLParser("<p>").css("p[")except SelectorError as e: # also a ValueError failed = Truefailed # TrueCatching ValueError covers both Parsec’s selector and XPath errors.
Attributes with no value
Section titled “Attributes with no value”# BeforeLexborHTMLParser("<input disabled>").css_first("input").attributes # {'disabled': None}# AfterHTMLParser("<input disabled>").css_first("input").attributes # {'disabled': ''}Code that tests attributes["disabled"] is None to mean “written without a value” needs to test == "" instead. A browser gives "" here too.
A node you’ve taken out
Section titled “A node you’ve taken out”H = "<ul><li>one <b>bold</b></li><li>two</li></ul>"
# Beforepage = LexborHTMLParser(H)first = page.css_first("li")first.decompose()first.text() # ''# Afterpage = HTMLParser(H)first = page.css_first("li")bold = first.css_first("b")first.decompose()first.text(), bold.text() # ('', '')first.tag # 'li'Both read as empty after decompose(). Where they differ is remove(): in selectolax it’s another name for decompose(), and in Parsec it keeps the node whole so you can put it somewhere else.
# Afterpage = HTMLParser(H)ul = page.css_first("ul")first = page.css_first("li")first.remove()first.text() # 'one bold'ul.insert_child(first, move=True)ul.html # '<ul><li>two</li><li>one <b>bold</b></li></ul>'Share one page between threads
Section titled “Share one page between threads”selectolax wants a parser per thread, so a page read by eight workers gets parsed eight times. With Parsec it’s parsed once:
# Afterfrom concurrent.futures import ThreadPoolExecutorpage = HTMLParser("<p><a href=/1>1</a><a href=/2>2</a></p>" * 1000)queries = ["a", "p", "a[href$='1']", "p > a:last-child"]with ThreadPoolExecutor(4) as pool: counts = list(pool.map(lambda q: len(page.css(q)), queries))counts # [2000, 1000, 1000, 1000]Selectors selectolax can’t parse
Section titled “Selectors selectolax can’t parse”H = "<div lang=fr><p>bonjour</p></div><div lang=en><p>hello</p></div>"
# Beforetry: LexborHTMLParser(H).css("p:lang(fr)")except SelectolaxError: refused = Truerefused # True# After[p.text() for p in HTMLParser(H).css("p:lang(fr)")] # ['bonjour']XPath on the same tree
Section titled “XPath on the same tree”selectolax has no XPath, so this one is new. It answers as lxml would:
# Afterpage = HTMLParser("<ul><li data-sku=A1>Kettle<li data-sku=B2>Toaster</ul>")page.xpath("//li/@data-sku") # ['A1', 'B2']page.xpath("string(//li[@data-sku=$s])", s="B2") # 'Toaster'Bytes from the network
Section titled “Bytes from the network”selectolax reads bytes as UTF-8 unless you pass encoding=True. Parsec always sniffs, as a browser does: byte order mark, then the HTTP charset, then <meta>, then valid UTF-8, then windows-1252.
# Afterdata = "<meta charset=windows-1251><p>Привет</p>".encode("cp1251")page = HTMLParser(data)page.css_first("p").text(), page.encoding # ('Привет', 'windows-1251')Pass the response’s charset as transport_encoding when you have it. Bytes and encodings has the order.
Gotchas
Section titled “Gotchas”decompose()then reading. If you kept a node and read it after decomposing its parent, selectolax gave you an empty element and so does Parsec. But nodes inside it read empty too in Parsec, andxpath()from one, or inserting one, raisesValueError.remove()no longer destroys. If you usedremove()to drop nodes you’ll never touch again, it still works; the nodes stay readable through any handle you kept.- Iterating while editing.
iter()andtraverse()take a list when you call them, so decomposing as you go doesn’t skip siblings. selectolax’s generators walked the live tree. strip_tagstakes selectors. In selectolax it matched tag names only, sostrip_tags([".ad"])did nothing. In Parsec it strips every.ad. If you ever passed it something that isn’t a bare tag name, check that’s what you want now..attrs.items()is a list. Code that callsnext()on it needsiter()first.- Nodes compare equal. Two
Nodeobjects for the same element are==and hash the same, so they work in sets and as dict keys.
Checking your pages
Section titled “Checking your pages”Before switching, run both on pages you already scrape and compare what your code extracts, not only the markup:
# Bothdef extract(page): return [(a.attributes.get("href"), a.text(strip=True)) for a in page.css("a")]
def same(html): return extract(LexborHTMLParser(html)) == extract(HTMLParser(html))
same("<p><a href=/x>x</a> <a href=/y> y </a>") # TrueFeed it a few hundred saved pages from your own crawl. Where it says False, print both sides: almost always it’s one of the differences above, an attribute without a value or a selector selectolax couldn’t run.
Then time it on those same pages with timeit. The figures above are one machine and one set of pages; your pages are the ones that count.