Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python HTML parser libraries turn HTML text into a tree of elements that code can search, read, and edit. A parser recovers from broken markup the way a browser does before a query API finds elements by CSS selector or XPath. These libraries let scrapers and AI agents pull text, links, and tables out of web pages.
Popularity
lxml has the most monthly downloads in this comparison, at 448.3M.
@_ConfigurableFilter(
xpath_list='HEADER_PERMALINKS_XPATH_LIST',
file_blacklist='HEADER_PERMALINKS_FILE_BLACKLIST',
)
def add_header_permalinks(fname, xpath_list=None, file_blacklist=None):
"""Post-process HTML via lxml to add header permalinks Sphinx-style."""
# Blacklist requires custom file handling file_blacklist = file_blacklist or []
if fname in file_blacklist:
return
with io.open(fname, 'r', encoding='utf-8-sig') as inf:
data = inf.read()
doc = lxml.html.document_fromstring(data)
# Get language for slugify try:
lang = doc.attrib['lang'] # <html lang="…">
except KeyError:
# Circular import workaround (utils imports filters) from nikola.utils import LocaleBorg
lang = LocaleBorg().current_lang
xpath_set = set()
if not xpath_list:
xpath_list = ['*//div[@class="e-content entry-content"]//{hx}']
for xpath_expr in xpath_list:
for hx in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
xpath_set.add(xpath_expr.format(hx=hx))
for x in xpath_set:
nodes = doc.findall(x)
for node in nodes:
parent = node.getparent()
if 'id' in node.attrib:
hid = node.attrib['id']
elif 'id' in parent.attrib:
# docutils: <div> has an ID and contains the header hid = parent.attrib['id']
else:
# Using force-mode, because not every character can appear in a # HTML id node.attrib['id'] = slugify(node.text_content(), lang, True)
hid = node.attrib['id']
new_node = lxml.html.fragment_fromstring(
'<a href="#{0}" class="headerlink" title="Permalink to this heading">¶</a>'.format(
hid
)
)
node.append(new_node)
with io.open(fname, 'w', encoding='utf-8') as outf:
outf.write('<!DOCTYPE html>\n' + lxml.html.tostring(doc, encoding='unicode'))
Beautiful Soup
Searches, navigates, and modifies HTML through a selected parser backend.
Downloads / mo
322.6M
Last release
4.15.0
License
MIT
Strengths
Combines tag searches with CSS.Use find_all and CSS selectors on the same parsed tree.
Retains source positions.Read sourceline and sourcepos with html.parser or html5lib.
Limitations
Parser choice changes broken trees.Choose a parser explicitly for consistent malformed-HTML handling.
Partial parsing excludes html5lib.SoupStrainer cannot skip input when using the html5lib backend.
def _readthedocs_reader(soup: Any, url: str, **kwargs) -> Tuple[str, Dict[str, Any]]:
"""Extract text from a ReadTheDocs documentation site."""
import requests
from bs4 import BeautifulSoup
links = soup.find_all("a", {"class": "reference internal"})
rtd_links = []
for link in links:
rtd_links.append(link["href"])
for i in range(len(rtd_links)):
if not rtd_links[i].startswith("http"):
rtd_links[i] = urljoin(url, rtd_links[i])
texts = []
for doc_link in rtd_links:
page_link = requests.get(doc_link)
soup = BeautifulSoup(page_link.text, "html.parser")
try:
text = soup.find(attrs={"role": "main"}).get_text()
except IndexError:
text = None
if text:
texts.append("\n".join([t for t in text.split("\n") if t]))
return "\n".join(texts), {}
html5lib
Builds HTML trees using WHATWG parsing and browser-compatible error recovery.
Downloads / mo
30.4M
Stars
1.2K
Last release
1.1
License
MIT
Strengths
Uses browser-style error recovery.Parse malformed HTML using the HTML specification’s recovery rules.
Can reject parse errors.Set strict=True to raise exceptions on parse errors.
Limitations
lxml trees lose some nodes.Root-level text or comments trigger DataLossWarning with the lxml tree builder.
lxml trees exclude PyPy.Choose another tree backend when running on PyPy.
def _parse_dls(self, body):
# All terms in <dl>s are treated as sections. # We traverse by <dl> - traversing by <dt> has shown in experiments to render a # different traversal order, which could make the tests more unstable. dls = body.css("dl")
for dl in dls:
# Use an iterator to select immediate descendants. dts = (node for node in dl.iter() if node.tag == "dt" and node.id)
# https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt # multiple <dt> elements in a row indicate several terms that are # all defined by the immediate next <dd> element. for dt in dts:
title, _id = self._parse_dt(dt)
dd = self._get_next_dd(dt)
# We only index a dt with an id attribute and an accompanying dd if not dd or not _id:
continue
# Create a copy of the node to avoid manipulating the # data structure that we're iterating over dd_copy = LexborHTMLParser(dd.html).body.child
# Remove all nested domains from dd_copy. # They are already parsed separately. for node in dd_copy.css("dl"):
# Traverse all <dt>s with an ID (the ones we index!) for _dt in node.css('dt[id]:not([id=""])'):
# Fetch adjacent <dd>s and remove them _dd_dt = self._get_next_dd(_dt)
if _dd_dt:
_dd_dt.decompose()
# Remove the <dt> too _dt.decompose()
# The content of the <dt> section is the content of the accompanying <dd> content = self._parse_content(dd_copy.text())
yield (
dd,
dt,
{
"id": _id,
"title": title,
"content": content,
},
)
parsel
Extracts data from HTML and XML with XPath and CSS selectors.
def redirect_url(self, source_locale=settings.LANGUAGE_CODE):
"""If I am a redirect, return the URL to which I redirect.
Otherwise, return None.
"""
# If a document starts with REDIRECT_HTML and contains any <a> tags # with hrefs, return the href of the first one. This trick saves us # from having to parse the HTML every time. if self.is_redirect:
anchors = PyQuery(self.html)("a[href]")
if anchors:
# Articles with a redirect have a link that has the locale # hardcoded into it, and so by simply redirecting to the given # link, we end up possibly losing the locale. So, instead, # we strip out the locale and replace it with the original # source locale only in the case where an article is going # from one locale and redirecting it to a different one. # This only applies when it's a non-default locale because we # don't want to override the redirects that are forcibly # changing to (or staying within) a specific locale. full_url = anchors[0].get("href")
(dest_locale, url) = split_into_language_and_path(full_url)
if source_locale != dest_locale and dest_locale == settings.LANGUAGE_CODE:
return f"/{source_locale}{url}"
return full_url
def main() -> bool:
html_session = HTMLSession()
response = html_session.get(PYPY_CHECKSUMS)
page = response.html
checksum_blocks = page.find("pre.literal-block")
for csum_block in checksum_blocks:
python_version, pypy_version = parse_pypy_ver(csum_block.text)
py_it = f"pypy{python_version}-{pypy_version}"
if py_it not in EXCLUDED_RELEASES:
vbin_path = OUT_DIR.joinpath(py_it)
vsrc_path = OUT_DIR.joinpath(py_it+"-src")
kwargs = None
for ps in ((vbin_path, SCRIPT_BIN), (vsrc_path, SCRIPT_SRC)):
if not ps[0].is_file():
kwargs = kwargs or parse_checksums_ext(csum_block.text)
code = ps[1].format(
version_pypy=pypy_version,
version_python=python_version,
ensurepip="ensurepip" if not python_version == "2.7" else "ensurepip_lt21",
**kwargs # which are:
# checksum_aarch64 # checksum_linux32 # checksum_linux64 # checksum_osarm64 # checksum_osx64 # checksum_src # file_ext )
if not args.dry_run:
with open(file=ps[0], mode="w", encoding="utf-8") as f:
f.write(code)
f.close()
else:
print(f"---- DRY RUN SCRIPT FOR {ps[0]} ----")
print(code)
FAQ
Beautiful Soup suits most scraping, with tag navigation over a choice of parser backends. lxml suits fast parsing with full XPath. selectolax suits high-volume parsing with CSS selectors.
Beautiful Soup searches, navigates, and modifies HTML through a parser backend such as the built-in html.parser, lxml, or html5lib. The backend decides how it recovers from broken markup.
Scrapling is a web scraping framework with CSS and XPath extraction. It can relocate elements after a page layout changes by matching their structure.
lxml parses quickly and supports full XPath and element editing. Beautiful Soup offers a friendlier search API and can use lxml as its parser backend.
selectolax parses HTML with the Lexbor engine and queries the tree with CSS selectors. It has no full XPath evaluator.
For coding agents
Found your HTML parser library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.