BeautifulSoup, lxml or selectolax: picking a Python HTML parser

The library under every selector

Copy an XPath out of Chrome DevTools, paste it into a Python script using lxml, run it against the same page, and get an empty list back. It’s one of the most common first-week scraping bugs, and the selector isn’t the problem. The HTML parser built a different tree from the one the browser built, and the path that exists in Chrome doesn’t exist in Python.

That’s the part of the parser choice people skip. Most comparisons of BeautifulSoup, lxml and selectolax jump straight to speed, quote a benchmark from someone else’s machine, and declare a winner. Speed matters at volume. But the questions that decide whether your extraction works at all come first: which tree does the library build from broken markup, which selector languages can you point at that tree, how pleasant is the API when you’re writing forty field extractors, and what does it drag into your dependency tree.

We’ve covered selector style and resilience elsewhere, in the pieces on CSS selectors versus XPath and on building a parser that survives redesigns. Those are about what you write. This is about the library that interprets it.

We run collectors in production that parse a lot of pages, and we’ve used all three libraries in different jobs. What follows sticks to the documented behaviour of each, and to trade-offs you can check yourself. There are no speed figures here, because a parse benchmark on one page set tells you very little about yours, and we’d rather show you how to measure than hand you a number.

One scoping note. All three libraries parse HTML you already have. None of them fetch pages or run JavaScript. If the data you want is injected by scripts after load, no parser choice will find it in the raw HTML, and that’s a rendering question for a different article.

What a parser actually does with your bytes

An HTML parser takes a stream of bytes, works out how to decode them into text, tokenises that text into tags, attributes and character data, and builds a tree of nodes from the tokens. Your selectors then walk that tree.

The tree-building step is where the libraries really differ. Well-formed HTML, where every tag opens and closes in order, produces the same tree in nearly any parser. Real pages are rarely well-formed. Unclosed paragraphs, stray closing tags, tables with no body element, inline elements wrapped around block elements, attributes with missing quotes, a second html tag halfway down from a badly injected widget. Browsers handle all of that because the HTML standard defines exactly how to recover from each error, and every modern browser follows the same algorithm.

A parser that implements that standard algorithm produces the tree a browser would. A parser that uses its own recovery rules produces a tree that’s usually similar and occasionally very different. The difference is invisible on clean pages and decisive on messy ones.

This is why “which parser is best” has no single answer. A parser that follows the standard is the right choice when you write selectors by looking at DevTools, because DevTools shows you the browser’s tree. A lenient parser with its own rules can be fine, and faster, when your targets produce reasonably clean markup and you write selectors against what the parser actually gives you.

It also means switching parsers is a behaviour change, not a refactor. The same selector can return different nodes after a switch, and the only reliable way to know is to run your extractors against saved pages with both.

BeautifulSoup is an API sitting on a backend

BeautifulSoup hands the parsing itself to someone else. The library provides a friendly tree API and delegates the actual parsing to a backend you name when you construct the soup. The documented choices are Python’s built-in html.parser, lxml, lxml-xml for XML, and html5lib.

That backend choice matters more than most tutorials admit. The BeautifulSoup documentation includes a section showing the same broken snippet parsed by each backend and producing different trees. html5lib follows the HTML standard and builds what a browser would, at the cost of being pure Python and slow. lxml is fast and lenient with its own recovery rules. html.parser needs no extra install and sits somewhere between the two on leniency. If you write BeautifulSoup(html) with no backend, you get whichever the library picks from what’s installed, along with a warning, and your results can change when someone installs a different package on the machine.

Once parsed, BeautifulSoup gives you find and find_all with keyword filters on tag name, attributes and text, attribute access that feels like a dictionary, .parent, .next_sibling and friends for navigation, and .select() for CSS selectors, which is powered by a separate package called soupsieve. It has no XPath support at all.

The tree itself is made of Python objects, and every navigation step runs Python code. That’s why BeautifulSoup is generally the slowest of the three for the same backend: the parse might happen in C via lxml, but the tree you walk is Python. The library’s own documentation recommends the lxml backend when speed matters.

Where it shines is forgiveness and discoverability. You can poke at an unfamiliar page in a notebook, try find_all with a lambda, print a pretty version of a subtree, and get to a working extractor quickly. It also has UnicodeDammit, a genuinely useful encoding detector for pages that lie about their charset.

lxml is libxml2 with a Python face

lxml is a binding to two C libraries, libxml2 and libxslt, which have been parsing XML and HTML for a very long time. The lxml.html module gives you an HTML parser, element objects with a compact API, and the full XPath 1.0 engine from libxml2.

XPath is lxml’s headline feature for scraping. You can select by position, walk up to ancestors, match on text content with contains() and normalize-space(), and express “the value cell in the row whose label cell says Price” in one expression. CSS selectors are also available through the cssselect package, which translates each CSS selector into an equivalent XPath. It’s a separate install, and it covers the common selectors but not every modern pseudo-class.

lxml’s HTML parser is libxml2’s, and libxml2’s HTML recovery rules predate the current HTML standard. It’s lenient and fast, and on most real pages it builds a tree close to what a browser shows. On some malformed inputs it differs, and the classic case is the table body, covered in the next section.

The element API is terse. el.get("href") for attributes, el.text for the text before the first child, el.tail for the text after the element’s own closing tag, and el.text_content() to flatten everything inside. The text-and-tail model trips people up the first time, because the text between two child elements belongs to the tail of the first child rather than to the parent. Once you’ve seen it, it makes sense. Before you’ve seen it, it produces missing fragments.

Scrapy’s selector library, parsel, is built on lxml and wraps it with a combined CSS and XPath interface. If you work in Scrapy, you’re already using lxml whether you chose it or not, and parsel on its own is a reasonable way to get lxml’s engine with a friendlier API outside Scrapy.

selectolax is a thin binding to a fast engine

selectolax is the youngest of the three. It’s a Cython binding to C HTML engines, and it ships two parser classes: HTMLParser, backed by the Modest engine, and LexborHTMLParser, backed by Lexbor. The project steers new users toward the Lexbor backend, and Lexbor is written to follow the HTML standard’s parsing algorithm, which means it builds trees that match what a browser builds.

The API is deliberately small. tree.css(selector) returns matching nodes, tree.css_first(selector) returns the first or None, node.text() returns text with options for stripping and separators, and node.attributes is a dictionary. There’s navigation through parent, next, child and an iterator over descendants, and you can remove nodes you don’t want before extracting text, which is handy for stripping scripts and navigation before pulling an article body.

What it doesn’t have is XPath. Selection is CSS only. That’s a real constraint for selectors that need to reason about text content or climb to ancestors, and you work around it in Python: select candidates with CSS, then filter them with a comprehension that checks text or walks up with .parent.

The appeal is a standard-compliant tree at native speed with a small surface area. For a collector that runs the same set of CSS selectors against a high volume of pages, that combination is hard to beat, and the small API means less to learn and fewer ways to write a slow extractor by accident.

The trade-off is a smaller community. Fewer answers exist on forums, fewer tutorials, and when something odd happens you’re more likely to be reading the source or the engine’s issue tracker. That’s worth weighing honestly if the person maintaining the collector after you is less comfortable doing that.

Malformed HTML and whose tree you get

The table body is the cleanest example of the tree mismatch, and it’s worth walking through because it explains so many “works in the browser, fails in Python” bugs.

The HTML standard says a tr directly inside a table goes inside an implied tbody. So when a page ships <table><tr><td>, every browser inserts a tbody element, and DevTools shows it. Right-click, copy XPath, and you get a path with tbody in it. A standard-compliant parser like html5lib or Lexbor inserts the same tbody, so that path works. libxml2’s HTML parser doesn’t insert it, so in lxml the tr sits directly under table and the copied path finds nothing.

The same kind of divergence shows up with other recovery cases: a block element inside a paragraph that the standard says implicitly closes the paragraph, a form nested inside another form, content after a stray </html>, or a table with text floating between rows that the standard hoists outside the table. Each is rare on any single site. Across a few hundred targets, you’ll meet most of them.

There are two sane responses. One is to use a standard-compliant parser, Lexbor through selectolax or html5lib through BeautifulSoup, so the tree you query matches the tree you inspected. The other is to use lxml and never write selectors from DevTools directly, instead printing or inspecting the tree lxml actually built and writing against that. Both work. Mixing them, writing selectors against the browser and running them against lxml, is where the empty lists come from.

A third approach we like for fragile extractors is to avoid depending on the ambiguous structure at all. Anchor on stable attributes, IDs, or embedded JSON rather than on the exact path through a table, and the parser’s recovery rules matter much less. That’s the resilience argument from the redesigns piece, and it applies doubly when you’re not sure whose tree you’re in.

Selector support side by side

What you can express decides how much Python you write around the selectors.

BeautifulSoup gives you its own filter API through find and find_all, which accepts tag names and attribute dictionaries, regular expressions, and arbitrary Python functions too. That last one is powerful: any predicate you can write in Python is a selector. It also gives you CSS through soupsieve, which has broad support for modern CSS including :has(), :is() and a number of custom pseudo-classes such as :-soup-contains() for matching text. No XPath.

lxml gives you full XPath 1.0 natively and CSS through cssselect. XPath 1.0 is old, but for scraping it covers nearly everything: axes to go up and sideways, predicates on text, selection by position, and the string functions you’d expect. You can also register custom XPath functions and use EXSLT regular expressions, though at that point most teams are better off doing the logic in Python.

selectolax gives you CSS through the engine, and nothing else. Its CSS support is solid for the selectors scrapers use most, attribute selectors, descendant and child combinators, :nth-child and friends. Text matching and ancestor logic move into Python.

In practice this shapes code style. An lxml extractor tends to be a list of XPath strings, each doing a lot. A selectolax extractor tends to be a short CSS selector followed by a line or two of Python. A BeautifulSoup extractor lands somewhere between, often mixing select with find calls. None of these is wrong. What matters is that the team maintaining the code can read it, and that the selectors survive your test suite of saved pages.

If you already have a large body of XPath selectors, that’s a strong reason to stay on lxml or parsel. Rewriting them into CSS plus Python for a speed gain you haven’t measured is rarely worth it.

Ergonomics when you are writing forty extractors

A parser you touch once a year can be awkward. One you write forty field extractors against every quarter needs to be pleasant, because awkward APIs breed copy-pasted helper functions that drift.

Text extraction is where the three feel most different. BeautifulSoup’s get_text() joins all descendant strings, with a separator and strip option. lxml has text_content() for the flattened string, plus the text and tail model when you need fragments. selectolax has text() with deep, separator and strip parameters. All three will happily give you a price with a newline and six spaces inside it if you don’t normalise, so every production extractor needs a whitespace-collapsing step regardless.

Missing elements are the other daily concern. BeautifulSoup’s find returns None, and chaining .find(...).get_text() on a missing element raises an AttributeError, which is a common source of crashes in hastily written collectors. selectolax’s css_first also returns None by default, and it takes a default argument. lxml’s xpath() always returns a list, so a missing element is an empty list, and you index into it carefully. Whatever you choose, wrap field extraction in a small helper that returns a typed empty value and logs which selector missed, so a missing field is data rather than an exception.

Attribute access is roughly equal. Navigation is richest in BeautifulSoup, which has named properties for every direction and a find_parent method. lxml has getparent(), getnext(), getprevious(), and XPath axes. selectolax has the basics.

Debugging favours BeautifulSoup. prettify() shows a readable subtree, and the objects print sensibly in a notebook. lxml’s etree.tostring(el, pretty_print=True) does the same job with more typing. selectolax nodes have .html for the raw markup of a subtree.

For exploratory work on an unfamiliar site, we reach for BeautifulSoup in a notebook almost every time, even when the production extractor ends up in something else.

Encoding and the bytes you hand it

Before a parser can build a tree, the bytes have to become text, and scraped pages lie about their encoding more often than you’d expect. A page declares UTF-8 in a meta tag and serves Windows-1252. The HTTP header says one thing and the meta tag says another. An old page has no declaration at all.

How each library handles this depends on whether you give it bytes or a string. If you pass a Python string, the decoding already happened, probably in your HTTP client, and the parser trusts it. If that decode was wrong, every accented character in the tree is already garbled and no parser can recover it.

BeautifulSoup accepts bytes and runs them through UnicodeDammit, which checks for a byte order mark, declared encodings, and then falls back to detection. It records what it decided in original_encoding, which is worth logging. It’s one of the better reasons to use BeautifulSoup at the edges of a pipeline, where input quality is unknown.

lxml, given bytes, looks for an encoding declaration in the document and otherwise makes its own assumption. Given a string that still contains an XML-style encoding declaration, it raises an error, which catches people converting pages to strings before parsing. You can pass an explicit encoding to the parser when you know better than the page does.

selectolax accepts both strings and bytes. When you’re not sure about the input, the safest pattern is the same for all three: decide the encoding once, at the fetch layer, using the HTTP header, the meta declaration and a detector in that order, log the decision, and hand the parser a decoded string. That keeps encoding bugs in one place instead of three.

Store the raw bytes too, as the reparsing piece argues. If you later discover a whole source was decoded wrong, raw bytes let you fix it without refetching.

Dependency weight and what it drags in

Parser choice is also an install choice, and it matters more in some environments than others.

BeautifulSoup is pure Python. On its own, with html.parser, it installs anywhere Python runs, including restricted environments where compiled packages are awkward. It pulls in soupsieve for CSS. Adding a faster backend means also installing lxml, and adding the standard-compliant one means installing html5lib, which is pure Python too.

lxml is a compiled extension bundling or linking libxml2 and libxslt. Binary wheels are published for the mainstream platforms and Python versions, so in most environments it’s a quick install. When a wheel isn’t available, for a very new Python release or an unusual platform, it falls back to building from source, which needs the C libraries and headers present and is where lxml’s old reputation for painful installs comes from. It’s also a large package relative to the others, which matters a little for small container images and serverless bundles. One more change worth knowing: the HTML cleaning module that used to live inside lxml was split into a separate package, lxml_html_clean, so code that imports lxml.html.clean may need that extra dependency on recent versions.

selectolax is also a compiled extension with binary wheels for mainstream platforms. It’s smaller than lxml and has no runtime Python dependencies of its own. The same caveat applies about new Python releases and unusual platforms: if the wheel you need isn’t published yet, you’re building from source.

For most server deployments on common Linux images, none of this is a real constraint. It becomes one when you run in a locked-down environment, ship to an unusual architecture, or upgrade Python the week it’s released. Pin versions, build images in CI, and the install question mostly goes away.

Speed without anyone else’s benchmark

Parse speed is the question everyone asks, and a published benchmark is the answer everyone quotes. The honest position is that the ordering is well understood from the architecture and that the size of the gap on your workload is something only you can measure.

Architecturally, selectolax and lxml parse in C and build their trees in C, so parsing and selection are fast. BeautifulSoup builds a tree of Python objects on top of whatever backend parsed the page, and every navigation step is Python, so it does more work per page for the same result. html5lib is pure Python end to end and slower again. That ordering is consistent with what the libraries’ own documentation says, and with what you’ll see if you time them.

Whether the gap matters depends on where your time goes. For a collector that fetches pages through a proxy, the network round trip usually dwarfs the parse, and a slower parser costs you close to nothing in wall-clock terms. For a job that reparses millions of stored pages from disk, parsing is most of the work and a faster parser directly shortens the run and the compute bill.

So measure on your own pages. Take a few hundred saved pages from your real targets, since page size and messiness vary enormously between sites. For each library, time the parse and your actual field extraction together, because a fast parse followed by clumsy extraction can lose to a slower parse with efficient selectors. Run it several times and discard the first run. Check peak memory while you’re there.

Then compare that per-page cost to your per-page fetch time. If parsing is a small fraction, choose on ergonomics and tree correctness. If it’s a large fraction, speed earns a much bigger vote.

Memory and very large documents

Most pages are small enough that memory doesn’t matter. The exceptions are big: a category page with thousands of items, a sitemap-like listing, a data dump published as one giant HTML table, or an XML product feed that runs to hundreds of megabytes.

All three libraries build the whole tree in memory by default. The Python-object tree BeautifulSoup builds takes considerably more memory than a C tree for the same document, which is one more reason it struggles on very large pages. If you’re parsing big documents in a worker pool, per-worker memory can become the thing that limits your concurrency.

There are a few tools for this. BeautifulSoup’s SoupStrainer lets you parse only the elements you care about, such as only the table with a particular ID, which cuts both time and memory when the useful part is a small slice of a big page. It doesn’t work with every backend, notably not html5lib, so check the documentation for your combination.

lxml has iterparse for incremental parsing, which is the right tool for large XML feeds: you process each product element as it completes and then clear it, so memory stays flat no matter how long the feed is. For HTML it’s less useful, because HTML recovery often needs context, but for XML feeds it’s the standard pattern.

With selectolax, the usual move is to extract what you need quickly and let the tree go, or to strip large irrelevant subtrees such as scripts and inline SVG before walking the rest.

And in any library, don’t hold trees longer than you need. A worker that keeps a reference to every parsed tree in a list for later processing is a memory leak by design. Extract into plain dictionaries, drop the tree, move on.

Choosing a default for your kind of job

Here’s where we land, and we’d defend it.

For a high-volume collector that runs a fixed set of CSS selectors against many pages, selectolax with the Lexbor backend is our default. You get a standard-compliant tree, so DevTools and Python agree, and native speed with a small API. The lack of XPath costs a few lines of Python per tricky field, which is a price we’re happy to pay.

For anything built on Scrapy, or any codebase with a large existing library of XPath selectors, lxml through parsel is the right choice. You already have it, XPath 1.0 is expressive, and the tree mismatch is manageable once the team knows to write selectors against lxml’s tree rather than the browser’s. Don’t rewrite working XPath for a speed gain nobody has measured on your workload.

For exploration, one-off jobs, messy inputs of unknown encoding, and teaching someone new to scraping, BeautifulSoup is still the easiest place to start. Use it with the lxml backend for speed, or with html5lib when you need browser-identical trees on a small number of pages. It’s a fine production choice for low-volume jobs where readability outweighs throughput.

What we’d argue against is using BeautifulSoup with no backend specified, because your results depend on whatever happens to be installed, and using lxml with selectors copied straight from DevTools, because that’s the empty-list bug waiting to happen.

Switching later without breaking extraction

Whatever you pick, you may want to change it. A job outgrows BeautifulSoup, or a new target breaks lxml’s tree in a way that matters. Planning for that is cheap.

Keep parsing behind a small interface. A function that takes a decoded page and returns a record, with field extractors that call a thin helper for “first match text” and “all matches attribute”, means the library appears in one module. Swapping it touches that module and the selectors, not every scraper.

Keep a saved-page test suite for every target, as the testing pieces in this series describe: a set of real pages with the records you expect from each. Before switching parsers, run the whole suite on both and diff the output field by field. Differences fall into three buckets. Some are whitespace, which your normaliser should absorb. Some are selectors that relied on one parser’s tree, which you rewrite. And occasionally the new parser finds data the old one missed, because its tree matched the browser’s where the old one didn’t, which is a pleasant surprise worth noting.

Switch one target at a time behind a config flag, watch field completeness for that target for a few runs, then move on. A parser change across every target at once, with no per-target rollback, turns a small behaviour change into a very long afternoon.

And write down which parser each target uses and why. The next person to look at a selector that seems to ignore tbody will want to know it was written for lxml on purpose.

If you’re weighing up the rest of the collection stack around the parser, from fetching to storage, the full set of guides is at Data Research Tools.

Get new guides and videos first — join the Telegram channel.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *