Typing Stubs for BeautifulSoup4

4.12.0.20250516 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `beautifulsoup4` with type hints. With `types-beautifulsoup4` installed, a type checker will correctly infer the types of `soup`, `title_tag`, and `paragraph_tag` objects, enabling better autocompletion and error detection. Note the use of `| None` for `find()` results, as elements might not be present.

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}")

view raw JSON →