Moving from Beautiful Soup
Beautiful Soup and Parsec both hand you a tree to search and change, but they ask you to search it differently. Beautiful Soup’s habit is find_all() with keyword filters and soup.div.a shorthand; Parsec’s is CSS selectors and XPath. Most of moving is turning one into the other, and this page does that for the things scrapers do most.
Every example runs as written: the Beautiful Soup half against beautifulsoup4 4.15.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. Beautiful Soup’s tree depends on the parser you give it. With
html.parser, the default most code uses,<ul><li>one<li>two</ul>comes out with the secondliinside the first. Parsec follows the HTML Standard, so you get what a browser’s DOM inspector shows. Tree shapes has examples. - Speed. Parsec’s parser is written in Rust and its selectors run there too. We haven’t published a benchmark against Beautiful Soup, so there’s no figure to quote here; Checking your pages shows how to time both on your own pages, which is the number you need anyway. For scale, Parsec is 1.6 times as fast as selectolax at parsing from Python (Python speed), and selectolax is the library people usually switch to from Beautiful Soup for speed.
- Threads. One parsed page can be queried by many threads at once, with the GIL let go while it works, and with no GIL at all on free-threaded Python 3.14t.
- XPath on the same tree, answering as lxml does.
Reasons to stay, or to keep Beautiful Soup for some jobs:
- Search by Python.
find_all()takes functions, regular expressions and lists as filters. Parsec doesn’t; you select broadly and filter in Python, as below. - Output.
prettify()and Beautiful Soup’s formatters have no Parsec equivalent yet. - XML. Beautiful Soup with
features="xml"gives you the same API on XML. Parsec’sparsec_html.xmlparses XML, but read-only and without selectors. - Pure Python. Beautiful Soup with
html.parserinstalls anywhere Python does. Parsec ships wheels for Linux, macOS and Windows on x86-64 and ARM; anywhere else pip needs Rust 1.88 to build it.
What maps to what
Section titled “What maps to what”| Beautiful Soup 4.15 | Parsec |
|---|---|
BeautifulSoup(html, "html.parser") |
HTMLParser(html) |
BeautifulSoup(html, "html5lib") |
HTMLParser(html), the same tree |
soup.find("a"), soup.a |
page.css_first("a") |
soup.find_all("a") |
page.css("a") |
find_all("a", href=True) |
css("a[href]") |
find_all("li", class_="sale") |
css("li.sale") |
find_all(attrs={"data-sku": "A1"}) |
css("[data-sku=A1]") |
find_all(["h1", "h2"]) |
css("h1, h2") |
find_all(string=re.compile(...)), function filters |
css(...), then filter in Python |
select(sel), select_one(sel) |
css(sel), css_first(sel) |
tag.get_text() |
node.text() |
tag.get_text(" ", strip=True) |
node.text(separator=" ", strip=True, skip_empty=True) |
tag.string |
node.text(), or node.text(deep=False) for its own text only |
tag["href"], tag.get("href") |
node.attrs["href"], node.attrs.get("href") |
tag.attrs |
node.attributes (a new dict) or node.attrs (live) |
tag["class"], a list |
node.attrs["class"], a string: split it yourself |
tag.name |
node.tag |
tag.parent, next_sibling, previous_sibling |
node.parent, node.next, node.prev |
tag.children, tag.contents |
node.iter(include_text=True) |
tag.descendants |
node.traverse(include_text=True) |
find_parent("div") |
walk parent and test node.tag, or XPath ancestor::div[1] |
find_next_sibling("li") |
node.xpath("following-sibling::li[1]") |
decompose() |
decompose() |
extract() |
remove() |
unwrap(), replace_with(...) |
unwrap(), replace_with(...) |
soup.new_tag("li") |
page.create_node("li") |
tag.append(x), insert_before, insert_after |
node.insert_child(x), insert_before, insert_after |
tag.string = "x" |
node.inner_html = "", then node.insert_child("x") |
str(tag) |
node.html |
tag.decode_contents() |
node.inner_html |
prettify() |
not yet |
BeautifulSoup(data, from_encoding=...) |
HTMLParser(data, transport_encoding=...) |
soup.original_encoding |
page.encoding |
API differences
Section titled “API differences”- Searching is by selector. Anything
find_all()can do with tag names and attribute values, a selector does in one string. Where you passed a regular expression or a function, select the candidates and filter them in Python. - Text and comments are nodes, not strings. Beautiful Soup gives you
NavigableStringandCommentobjects. Parsec gives youNodes whosetagis-textor-comment; read them withtext_contentandcomment_content. nextandprevinclude text. As in Beautiful Soup, the sibling after an element is often whitespace. Skip it by checkingis_element_node, or ask XPath forfollowing-sibling::*[1].- No attribute shorthand.
soup.ul.li.ais a chain offind()s. In Parsec it’spage.css_first("ul li a"), one call, and it doesn’t stop at the firstulthat has noliwith ana. classis one string. Beautiful Soup splits multi-valued attributes into lists. Parsec gives every attribute as written.- Missing attributes.
tag["x"]andnode.attrs["x"]both raiseKeyError.node.attrs.sget("x")gives""instead ofNone.
Side by side
Section titled “Side by side”Parse and read a listing
Section titled “Parse and read a listing”H = '<title>Shop</title><ul><li class="item sale" 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 bs4 import BeautifulSoupsoup = BeautifulSoup(H, "html.parser")soup.title.string # 'Shop'[(li["data-sku"], li.a.get_text(), li.find("span", class_="price").get_text()) for li in soup.find_all("li", class_="item")]# Afterfrom parsec_html import HTMLParserpage = HTMLParser(H)page.css_first("title").text() # 'Shop'[(li.attrs["data-sku"], li.css_first("a").text(), li.css_first("span.price").text()) for li in page.css("li.item")]Run that H through both and look at the shapes: Beautiful Soup’s html.parser nests the second li inside the first, because nothing closed it. It still finds both, since find_all searches the whole tree, but soup.li.get_text() would give you both items’ text.
# Beforesoup.li.get_text(" ", strip=True) # 'Kettle £24 Toaster £31'# Afterpage.css_first("li").text(separator=" ", strip=True, skip_empty=True) # 'Kettle £24'Every link with an href
Section titled “Every link with an href”H = "<p><a href=/a>a</a> <a name=top>top</a> <a href=https://x.example/>x</a></p>"
# Before[a["href"] for a in BeautifulSoup(H, "html.parser").find_all("a", href=True)] # ['/a', 'https://x.example/']# After[a.attrs["href"] for a in HTMLParser(H).css("a[href]")] # ['/a', 'https://x.example/']XPath gets the strings straight back:
# AfterHTMLParser(H).xpath("//a/@href") # ['/a', 'https://x.example/']Filter by text
Section titled “Filter by text”find_all takes a regular expression for string. Select, then filter:
import reH = "<ul><li>Kettle, 1.7 L</li><li>Toaster</li><li>Kettle, 1 L</li></ul>"
# Before[li.get_text() for li in BeautifulSoup(H, "html.parser").find_all("li", string=re.compile("Kettle"))] # ['Kettle, 1.7 L', 'Kettle, 1 L']# After[li.text() for li in HTMLParser(H).css("li") if re.search("Kettle", li.text())] # ['Kettle, 1.7 L', 'Kettle, 1 L']For a plain substring, XPath can do it in the query: page.xpath("//li[contains(., 'Kettle')]").
Text without the whitespace
Section titled “Text without the whitespace”H = "<div>\n <h1>Title</h1>\n <p>First para.</p>\n</div>"
# BeforeBeautifulSoup(H, "html.parser").div.get_text("|", strip=True) # 'Title|First para.'# AfterHTMLParser(H).css_first("div").text(separator="|", strip=True, skip_empty=True) # 'Title|First para.'Leave out skip_empty=True and the whitespace between tags comes through as empty pieces, so you’d get '|Title||First para.|'.
Siblings and parents
Section titled “Siblings and parents”H = "<table><tr><th>Price</th><td>£24</td></tr><tr><th>Weight</th><td>1.2 kg</td></tr></table>"
# Beforesoup = BeautifulSoup(H, "html.parser")soup.find("th", string="Weight").find_next_sibling("td").get_text() # '1.2 kg'# Afterpage = HTMLParser(H)page.xpath("string(//th[.='Weight']/following-sibling::td[1])") # '1.2 kg'Or with selectors and next, when the cells sit side by side:
# Afterth = next(th for th in page.css("th") if th.text() == "Weight")th.next.text() # '1.2 kg'th.parent.tag # 'tr'That parent is a tr whose parent is a tbody in Parsec, as in a browser. Beautiful Soup’s html.parser doesn’t add one.
Clean a page
Section titled “Clean a page”H = '<article><p>Read <b>this</b>.</p><script>track()</script><div class=ad>Buy!</div></article>'
# Beforesoup = BeautifulSoup(H, "html.parser")for tag in soup.select("script, .ad"): tag.decompose()soup.b.unwrap()str(soup.article) # '<article><p>Read this.</p></article>'# Afterpage = HTMLParser(H)for node in page.css("script, .ad"): node.decompose()page.css_first("b").unwrap()page.css_first("article").html # '<article><p>Read this.</p></article>'page.strip_tags(["script", ".ad"]) and page.unwrap_tags(["b"]) do the same in one call each.
Add and change elements
Section titled “Add and change elements”# Beforesoup = BeautifulSoup("<ul><li>a</li></ul>", "html.parser")li = soup.new_tag("li", attrs={"class": "new"})li.string = "b & c"soup.ul.append(li)soup.ul.li["data-x"] = "1"str(soup.ul) # '<ul><li data-x="1">a</li><li class="new">b & c</li></ul>'# Afterpage = HTMLParser("<ul><li>a</li></ul>")ul = page.css_first("ul")li = page.create_node("li")li.attrs["class"] = "new"li.insert_child("b & c") # a str goes in as text, never parsedul.insert_child(li, move=True)ul.css_first("li").attrs["data-x"] = "1"ul.html # '<ul><li data-x="1">a</li><li class="new">b & c</li></ul>'insert_child(li) without move=True would insert a copy. To insert markup rather than text, parse it as a fragment and pass its node:
# Afterul.insert_child(HTMLParser("<li><b>d</b></li>", is_fragment=True, fragment_tag="ul").root)ul.html # '<ul><li data-x="1">a</li><li class="new">b & c</li><li><b>d</b></li></ul>'To replace an element’s text, as tag.string = ... does, empty it and insert:
# Aftera = HTMLParser("<a href=/a>old <b>text</b></a>").css_first("a")a.inner_html = ""a.insert_child("new & improved")a.html # '<a href="/a">new & improved</a>'Bytes from the network
Section titled “Bytes from the network”data = "<meta charset=windows-1251><p>Привет</p>".encode("cp1251")
# Beforesoup = BeautifulSoup(data, "html.parser")soup.p.get_text(), soup.original_encoding # ('Привет', 'windows-1251')# Afterpage = HTMLParser(data)page.css_first("p").text(), page.encoding # ('Привет', 'windows-1251')With no <meta> and no charset, the two guess differently. Beautiful Soup asks UnicodeDammit, which guesses with cchardet, chardet or charset-normalizer, whichever is installed, and falls back to windows-1252. Parsec does what a browser does: valid UTF-8 is UTF-8, and anything else is windows-1252 unless you pass default_encoding. When you have the HTTP Content-Type, pass its charset as transport_encoding, and the guess doesn’t come into it. Bytes and encodings has the whole order.
Tree shapes
Section titled “Tree shapes”Beautiful Soup’s tree is its parser’s tree. These come from the same input through each:
| Input | html.parser |
lxml |
html5lib and Parsec |
|---|---|---|---|
<ul><li>one<li>two</ul> |
second li inside the first |
two lis |
two lis |
<table><tr><td>1</table> |
no tbody |
no tbody |
tbody added |
<p>a<div>b</div>c</p> |
div inside p |
p closed before div, last p dropped |
p closed before div, empty p at the end |
<b>1<i>2</b>3</i> |
3 outside any i |
3 outside any i |
3 in a second i |
<a href=x>1<a href=y>2</a> |
nested links | two links | two links |
<svg viewBox="0 0 1 1"> |
viewbox |
viewbox |
viewBox |
If you used html5lib for its accuracy, Parsec gives the same trees. If you used html.parser or lxml, selectors that depended on their shapes can match differently: table > tr matches nothing in Parsec, because the tr is in a tbody. Write table tr, or tbody > tr.
Gotchas
Section titled “Gotchas”table > trfinds nothing; see above.soup.find()returnsNone, and so doescss_first(). Chained shorthand likesoup.div.a.textraisesAttributeErroron a missing link in both;css_first("div a")makes it one check.classis a string."sale" in node.attrs["class"]is a substring test. Use"sale" in node.attrs["class"].split(), or better, select.sale.get_text()and whitespace. Withoutskip_empty=True, Parsec keeps the whitespace-only pieces Beautiful Soup drops when you passstrip=True.<template>contents aren’t in the tree, as in a browser. Beautiful Soup with any parser shows them as children.- Copies by default.
insert_child(node)inserts a copy ofnode. Passmove=Trueto move it, asappenddoes in Beautiful Soup.
Checking your pages
Section titled “Checking your pages”Moving is a rewrite of the calls, so test what the code extracts, not the markup. Keep your Beautiful Soup scraper and your Parsec one side by side for a while, and run both over pages you’ve saved:
# Bothdef scrape_bs4(html): soup = BeautifulSoup(html, "html.parser") return [(a.get("href"), a.get_text(" ", strip=True)) for a in soup.find_all("a")]
def scrape_parsec(html): page = HTMLParser(html) return [(a.attrs.get("href"), a.text(separator=" ", strip=True, skip_empty=True)) for a in page.css("a")]
html = "<p><a href=/x>x</a> <a href=/y> y <b>z</b></a>"scrape_bs4(html) == scrape_parsec(html) # TrueWhere they disagree, print both. Most differences are the tree shapes above, and on those Parsec is the one that matches the browser.
Then time both on the same saved pages:
# Bothimport timeithtml = "<ul>" + "<li class=item><a href=/p>Product</a> <span class=price>£9</span></li>" * 2000 + "</ul>"bs4_s = min(timeit.repeat(lambda: scrape_bs4(html), number=1, repeat=3))parsec_s = min(timeit.repeat(lambda: scrape_parsec(html), number=1, repeat=3))Use your own pages rather than this one. A synthetic page measures a synthetic scraper.