Typing Stubs for BeautifulSoup4
types-beautifulsoup4 provides PEP 561 compliant type stubs for the beautifulsoup4 library, enabling static type checkers like MyPy, Pyright, and PyCharm to analyze code using BeautifulSoup4 for type correctness. This package specifically targets beautifulsoup4 versions up to 4.12.*. It is part of the typeshed project, which automatically releases updates to stub packages on PyPI, often in sync with the upstream library's releases or typeshed's internal machinery.
Warnings
- breaking Starting with `beautifulsoup4` version 4.13.0, the `beautifulsoup4` package itself includes type annotations. If you are using `beautifulsoup4` 4.13.0 or newer, you MUST uninstall `types-beautifulsoup4` to avoid potential conflicts or incorrect type checking behavior.
- gotcha Installing `types-beautifulsoup4` alone is not sufficient to run your code; you still need to install the `beautifulsoup4` runtime library. The `types-*` packages provide only type definitions, not the actual implementation.
- gotcha Type checkers may report `Any` types or incorrect type inference if there's a version mismatch between the installed `types-beautifulsoup4` package and your `beautifulsoup4` runtime library, or if the stub package is marked as 'partial'. This can lead to a loss of type checking precision.
- gotcha Typeshed, the source for `types-beautifulsoup4`, sometimes introduces stricter type annotations or changes that, while technically correct, might cause your existing code to fail type checking. This can happen even with minor updates to the stub package.
- gotcha Methods like `find()` and `find_all()` often return `None` if no matching element is found. Type checkers will correctly flag potential `None` access errors. Be explicit about handling optional return types in your code.
Install
-
pip install types-beautifulsoup4
Imports
- BeautifulSoup
from bs4 import BeautifulSoup
- Tag
from bs4.element import Tag
Quickstart
from bs4 import BeautifulSoup, Tag
html_doc: str = """
<html>
<head><title>The Title</title></head>
<body>
<p class="story">Hello World</p>
</body>
</html>
"""
soup: BeautifulSoup = BeautifulSoup(html_doc, 'html.parser')
# Accessing a tag with type hint
title_tag: Tag | None = soup.find('title')
if title_tag:
print(f"Title: {title_tag.text}")
# Accessing a paragraph with type hint
paragraph_tag: Tag | None = soup.find('p', class_='story')
if paragraph_tag:
print(f"Paragraph: {paragraph_tag.text}")