# Python HTML parser libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [lxml](#lxml) | 448.3M | 3.1K | Sep 2026 | BSD-3-Clause |
| [Beautiful Soup](#beautiful-soup) | 322.6M | Not on GitHub | Jun 2026 | MIT |
| [html5lib](#html-lib) | 30.4M | 1.2K | Jun 2020 | MIT |
| [selectolax](#selectolax) | 6.5M | 1.7K | Oct 2026 | MIT |
| [parsel](#parsel) | 3.8M | Not on GitHub | Sep 2026 | BSD-3-Clause |
| [Scrapling](#scrapling) | 1.5M | Not on GitHub | Nov 2026 | BSD-3-Clause |
| [PyQuery](#pyquery) | 1.4M | Not on GitHub | Jul 2026 | BSD-3-Clause |
| [Requests-HTML](#requests-html) | 398.2K | Not on GitHub | Feb 2019 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[lxml](#lxml) has the most monthly downloads in this comparison, at 448.3M.

## Capabilities

| Library | CSS selector queries | XPath queries |
| --- | --- | --- |
| [lxml](#lxml) | Via plugin | Yes |
| [Beautiful Soup](#beautiful-soup) | Yes | No |
| [html5lib](#html-lib) | Via plugin | Via plugin |
| [selectolax](#selectolax) | Yes | No |
| [parsel](#parsel) | Yes | Yes |
| [Scrapling](#scrapling) | Yes | Yes |
| [PyQuery](#pyquery) | Yes | Yes |
| [Requests-HTML](#requests-html) | Yes | Yes |

## Libraries

### lxml

[GitHub](https://github.com/lxml/lxml) · [PyPI](https://pypi.org/project/lxml) · [Docs](https://lxml.de/lxmlhtml.html)

Parses HTML into ElementTree-compatible elements with XPath and HTML-specific methods.

- Downloads / mo: 448.3M
- Stars: 3.1K
- Last release: 6.1.3
- License: BSD-3-Clause
- Capabilities: [From the lxml docs](https://lxml.de/lxmlhtml.html)

**Strengths**

- **Selects elements with XPath.** Query the parsed tree using XPath expressions.
- **Parses fragments as separate elements.** Use fragments_fromstring when input contains multiple top-level elements.

**Watch out for**

- **CSS selectors need another package.** Install cssselect before using lxml.cssselect.
- **Recovery risks missing content.** Validate extracted content before trusting heavily malformed input.

```sh
python3.13 -m pip install lxml==6.1.3
```

**getnikola/nikola** (2.7K stars)

[getnikola/nikola](https://github.com/getnikola/nikola) 

```python
@_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'))
```

[nikola/filters.py](https://github.com/getnikola/nikola/blob/b6931dc3122b1b37bbeeb0f0663f57833f911c09/nikola/filters.py) · [More projects using lxml →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20lxml%20for%20HTML%20parsing%20and%20element%20selection&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from lxml import html

document = html.fromstring("<h1>Hello</h1>")
print(document.text_content())

```

From [lxmlhtml.txt](https://lxml.de/lxmlhtml.html)

### Beautiful Soup

[PyPI](https://pypi.org/project/beautifulsoup4) · [Docs](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)

Searches, navigates, and modifies HTML through a selected parser backend.

- Downloads / mo: 322.6M
- Last release: 4.15.0
- License: MIT
- Capabilities: [From the Beautiful Soup docs](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)

**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.

**Watch out for**

- **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.

```sh
python3.13 -m pip install beautifulsoup4==4.15.0
```

**run-llama/llama_index** (52.9K stars)

[run-llama/llama_index](https://github.com/run-llama/llama_index) 

```python
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), {}
```

[llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/beautiful_soup_web/base.py](https://github.com/run-llama/llama_index/blob/99d7433f6f71888951379ccca9294e272442c832/llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/beautiful_soup_web/base.py) · [More projects using Beautiful Soup →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20beautifulsoup4%20for%20HTML%20parsing%20and%20element%20selection&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from bs4 import BeautifulSoup

document = BeautifulSoup("<h1>Hello</h1>", "html.parser")
print(document.h1.get_text())

```

From [doc.md](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)

### html5lib

[GitHub](https://github.com/html5lib/html5lib-python) · [PyPI](https://pypi.org/project/html5lib) · [Docs](https://html5lib.readthedocs.io/en/latest/html5lib.html)

Builds HTML trees using WHATWG parsing and browser-compatible error recovery.

- Downloads / mo: 30.4M
- Stars: 1.2K
- Last release: 1.1
- License: MIT
- Capabilities: [From the html5lib docs](https://html5lib.readthedocs.io/en/latest/html5lib.html)

**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.

**Watch out for**

- **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.

```sh
python3.13 -m pip install html5lib==1.1
```

**getnikola/nikola** (2.7K stars)

[getnikola/nikola](https://github.com/getnikola/nikola) 

```python
@apply_to_text_file
def html5lib_minify(data):
    """Minify with html5lib."""
    import html5lib
    import html5lib.serializer

    data = html5lib.serializer.serialize(
        html5lib.parse(data, treebuilder='lxml'),
        tree='lxml',
        quote_attr_values='spec',
        omit_optional_tags=True,
        minimize_boolean_attributes=True,
        strip_whitespace=True,
        alphabetical_attributes=True,
        escape_lt_in_attrs=True,
    )
    return data
```

[nikola/filters.py](https://github.com/getnikola/nikola/blob/b6931dc3122b1b37bbeeb0f0663f57833f911c09/nikola/filters.py) · [More projects using html5lib →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20html5lib%20for%20HTML%20parsing%20and%20element%20selection&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import html5lib

document = html5lib.parse("<h1>Hello</h1>")
print(document.tag)

```

From [README.rst](https://html5lib.readthedocs.io/en/latest/html5lib.html)

### selectolax

[GitHub](https://github.com/rushter/selectolax) · [PyPI](https://pypi.org/project/selectolax) · [Docs](https://selectolax.readthedocs.io/en/latest/lexbor.html)

Parses HTML with Lexbor and queries its tree using CSS selectors.

- Downloads / mo: 6.5M
- Stars: 1.7K
- Last release: 1.0.2
- License: MIT
- Capabilities: [From the selectolax docs](https://selectolax.readthedocs.io/en/latest/lexbor.html)

**Strengths**

- **Queries with complex CSS.** Use compound selectors to target matching nested elements.
- **Parses fragments without document wrappers.** Set is_fragment=True to avoid inserting synthetic document elements.

**Watch out for**

- **Template contents need separate traversal.** Use template_fragments; ordinary css queries skip template contents.

```sh
python3.13 -m pip install selectolax==1.0.2
```

**readthedocs/readthedocs.org** (8.4K stars)

[readthedocs/readthedocs.org](https://github.com/readthedocs/readthedocs.org) 

```python
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,
                },
            )
```

[readthedocs/search/parsers.py](https://github.com/readthedocs/readthedocs.org/blob/38dd30b02babe5890d38d2bb488f08cfeb97cf3c/readthedocs/search/parsers.py) · [More projects using selectolax →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20selectolax%20for%20HTML%20parsing%20and%20element%20selection&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from selectolax.lexbor import LexborHTMLParser

document = LexborHTMLParser("<h1>Hello</h1>")
print(document.css_first("h1").text())

```

From [README.md](https://selectolax.readthedocs.io/en/latest/lexbor.html)

### parsel

[GitHub](https://github.com/scrapy/parsel) · [PyPI](https://pypi.org/project/parsel) · [Docs](https://parsel.readthedocs.io/en/latest/usage.html)

Extracts data from HTML and XML with XPath and CSS selectors.

- Downloads / mo: 3.8M
- Last release: 1.12.1
- License: BSD-3-Clause
- Capabilities: [From the parsel docs](https://parsel.readthedocs.io/en/latest/usage.html)

```sh
python3.13 -m pip install parsel==1.12.1
```

**apify/crawlee-python** (9.7K stars)

[apify/crawlee-python](https://github.com/apify/crawlee-python) 

```python
@override
def find_links(self, parsed_content: Selector, selector: str, attribute: str) -> Iterable[str]:
    link: Selector
    urls: list[str] = []
    for link in parsed_content.css(selector):
        url = link.xpath(f'@{attribute}').get()
        if url:
            urls.append(url.strip())
    return urls
```

[src/crawlee/crawlers/_parsel/_parsel_parser.py](https://github.com/apify/crawlee-python/blob/db01ddcbf1cea39b6dbf08ec0b397eb68098d85d/src/crawlee/crawlers/_parsel/_parsel_parser.py) · [More projects using parsel →](https://dashboard.exa.ai/playground/search?q=parsel%20GitHub%20projects)

**Quickstart**

```python
from parsel import Selector

document = Selector(text="<h1>Hello</h1>")
print(document.css("h1::text").get())

```

From [usage.html](https://parsel.readthedocs.io/en/latest/usage.html)

### Scrapling

[GitHub](https://github.com/D4Vinci/Scrapling) · [PyPI](https://pypi.org/project/scrapling) · [Docs](https://scrapling.readthedocs.io/en/latest/parsing/selection/)

Scrapes the web through a high-performance Python framework.

- Downloads / mo: 1.5M
- Last release: 0.5.1
- License: BSD-3-Clause
- Capabilities: [From the Scrapling docs](https://scrapling.readthedocs.io/en/latest/parsing/selection/)

```sh
python3.13 -m pip install scrapling==0.5.1
```

**byungjunjang/web-crawler** (197 stars)

[byungjunjang/web-crawler](https://github.com/byungjunjang/web-crawler) 

```python
def select_items(url, selector, heal=False):
    storage = {"storage_file": "./fingerprints/elements_storage.db", "url": url}
    try:
        Path("./fingerprints").mkdir(exist_ok=True)
        page = plain_get(url, selector_config={"adaptive": True, "storage_args": storage})
        return page.css(selector, adaptive=heal, auto_save=True)
    except (OSError, sqlite3.Error) as exc:
        logger.warning(f"자가치유 저장소 사용 불가, 일반 셀렉터로 계속: {exc}")
        page = plain_get(url, selector_config={"adaptive": False})
        return page.css(selector)
```

[scripts/scrapling_reference.md](https://github.com/byungjunjang/web-crawler/blob/bbca7cad38b5efb5dd3f72cd1c10075efe6c637a/scripts/scrapling_reference.md) · [More projects using Scrapling →](https://dashboard.exa.ai/playground/search?q=scrapling%20GitHub%20projects)

**Quickstart**

```python
from scrapling.parser import Selector

document = Selector("<h1>Hello</h1>")
print(document.css("h1::text").get())

```

From [parser.py](https://api.github.com/repos/D4Vinci/Scrapling/contents/scrapling/parser.py?ref=v0.5.1)

### PyQuery

[GitHub](https://github.com/gawel/pyquery) · [PyPI](https://pypi.org/project/pyquery) · [Docs](https://pyquery.readthedocs.io/en/latest/api.html)

Queries HTML in Python with a jQuery-like API.

- Downloads / mo: 1.4M
- Last release: 2.1.0
- License: BSD-3-Clause
- Capabilities: [From the PyQuery docs](https://pyquery.readthedocs.io/en/latest/api.html)

```sh
python3.13 -m pip install pyquery==2.1.0
```

**mozilla/kitsune** (1.7K stars)

[mozilla/kitsune](https://github.com/mozilla/kitsune) 

```python
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
```

[kitsune/wiki/models.py](https://github.com/mozilla/kitsune/blob/d19fcdd98bb78863331b3c80f2a2dee880fcee9a/kitsune/wiki/models.py) · [More projects using PyQuery →](https://dashboard.exa.ai/playground/search?q=pyquery%20GitHub%20projects)

**Quickstart**

```python
from pyquery import PyQuery

document = PyQuery("<h1>Hello</h1>")
print(document("h1").text())

```

From [pyquery.py](https://api.github.com/repos/gawel/pyquery/contents/pyquery/pyquery.py?ref=2.1.0)

### Requests-HTML

[GitHub](https://github.com/psf/requests-html) · [PyPI](https://pypi.org/project/requests-html) · [Docs](https://requests.readthedocs.io/projects/requests-html/en/latest/)

Parses HTML with a human-friendly API.

- Downloads / mo: 398.2K
- Last release: 0.10.0
- License: MIT
- Capabilities: [From the Requests-HTML docs](https://requests.readthedocs.io/projects/requests-html/en/latest/)

```sh
python3.13 -m pip install requests-html==0.10.0 lxml-html-clean==0.4.6
```

**pyenv/pyenv** (45.2K stars)

[pyenv/pyenv](https://github.com/pyenv/pyenv) 

```python
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)
```

[plugins/python-build/scripts/add_pypy.py](https://github.com/pyenv/pyenv/blob/186b350c853042c5b943df053fe1b99a7c81e5a3/plugins/python-build/scripts/add_pypy.py) · [More projects using Requests-HTML →](https://dashboard.exa.ai/playground/search?q=requests-html%20GitHub%20projects)

**Quickstart**

```python
from requests_html import HTML

document = HTML(html="<h1>Hello</h1>")
print(document.find("h1", first=True).text)

```

From [requests_html.py](https://api.github.com/repos/psf/requests-html/contents/requests_html.py?ref=v0.10.0)

## FAQ

### Which Python HTML parser should I use?

[Beautiful Soup](#beautiful-soup) suits most scraping, with tag navigation over a choice of parser backends. [lxml](#lxml) suits fast parsing with full XPath. [selectolax](#selectolax) suits high-volume parsing with CSS selectors.

### What is Beautiful Soup?

[Beautiful Soup](#beautiful-soup) searches, navigates, and modifies HTML through a parser backend such as the built-in html.parser, lxml, or [html5lib](#html-lib). The backend decides how it recovers from broken markup.

### What is Scrapling?

[Scrapling](#scrapling) is a web scraping framework with CSS and XPath extraction. It can relocate elements after a page layout changes by matching their structure.

### Beautiful Soup vs lxml: which should I use?

[lxml](#lxml) parses quickly and supports full XPath and element editing. [Beautiful Soup](#beautiful-soup) offers a friendlier search API and can use lxml as its parser backend.

### What is selectolax?

[selectolax](#selectolax) parses HTML with the Lexbor engine and queries the tree with CSS selectors. It has no full XPath evaluator.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python HTML parser libraries Beautiful Soup lxml selectolax html5lib code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
