HOWTO · Python

How to Parse HTML Data in Python

Learn how to parse local HTML and extract elements or text in Python with Beautiful Soup, PyQuery, lxml, and jusText.

On this page

Python can parse HTML that you already have as a string or file, then select elements and extract their text or markup. A parser does not fetch a web page by itself: retrieve remote HTML separately if that is part of your application, and pass the response body to the parser. These examples use local strings so their inputs do not depend on a live site.

Run this example:

from html.parser import HTMLParser

class TextParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.parts = []

    def handle_data(self, data):
        text = data.strip()
        if text:
            self.parts.append(text)

parser = TextParser()
parser.feed("<h1>Guide</h1><p>Local HTML</p>")
print("\n".join(parser.parts))

Python’s standard library can handle simple parsing tasks. The sections below show libraries with APIs for tree navigation, selectors, and main-text extraction.

Parse HTML with Beautiful Soup

Install Beautiful Soup with pip install beautifulsoup4. Beautiful Soup builds a navigable tree from markup. Its html.parser backend is included with Python; you can choose another supported parser when your project needs one.

try:
    from bs4 import BeautifulSoup
except ImportError:
    print("Install beautifulsoup4 to run this example.")
else:
    html = "<article><h1>Guide</h1><p>Parse local HTML.</p></article>"
    soup = BeautifulSoup(html, "html.parser")
    print(soup.h1.get_text())
    print(soup.article.p.get_text())

Use find() or select_one() when you need a particular match. get_text() returns descendant text, while str(element) serializes the element with its tags. If a selector may have no match, check for None before accessing it. Beautiful Soup parses supplied content; it does not make network requests.

Select HTML Elements with PyQuery

Install PyQuery with pip install pyquery. It provides a jQuery-like interface for selecting nodes with CSS selectors. Pass the markup string directly to PyQuery, then call .text() on the selection to retrieve text rather than HTML tags.

try:
    from pyquery import PyQuery
except ImportError:
    print("Install pyquery to run this example.")
else:
    html = "<main><h1>Guide</h1><p class='note'>Local input</p></main>"
    document = PyQuery(html)
    print(document("h1").text())
    print(document(".note").text())

This is useful when the selection is naturally expressed as CSS selectors. A selection can match multiple nodes; .text() combines the selected text, so iterate over the selection if each match must be processed separately. PyQuery also parses only the HTML supplied to it.

Parse HTML with lxml

Install the HTML parser with pip install lxml. lxml.html.fromstring() parses a string into an element tree, and XPath can select nodes from that tree. The following example uses XPath so it does not depend on an additional CSS-selector package.

try:
    from lxml import html
except ImportError:
    print("Install lxml to run this example.")
else:
    source = "<main><a>First</a><div>Data</div><a>Second</a></main>"
    root = html.fromstring(source)
    for element in root.xpath(".//a | .//div"):
        print(element.text_content())

text_content() includes text nested under the selected element. XPath expressions return a list, including an empty list when nothing matches, so a loop naturally handles no matches. Choose XPath or CSS selectors according to the query you need; this example makes no general speed claim over other parsers.

Extract Main Text with jusText

Install jusText with pip install justext. It is designed to identify likely main-text paragraphs in page HTML, which is a different task from selecting a known element. Supply the HTML bytes and a stoplist for the document language. The output is a heuristic: page structure and language affect which paragraphs are classified as boilerplate or content.

try:
    import justext
except ImportError:
    print("Install justext to run this example.")
else:
    page = b"<html><body><article><p>A local article paragraph.</p></article></body></html>"
    paragraphs = justext.justext(page, justext.get_stoplist("English"))
    for paragraph in paragraphs:
        if not paragraph.is_boilerplate:
            print(paragraph.text)

This local input avoids a request to an external website. For downloaded pages, fetch and check the response in your own code before passing its content to jusText. Do not treat extracted paragraphs as a guaranteed clean transcript; inspect the result for the pages and languages you process.

Use EHP to Parse HTML

EHP is another parser name found in older examples, but the package and API are not established by the available material for this article. The earlier sample’s function and method descriptions were inconsistent, so this guide does not present that sample as a runnable recipe or claim that EHP handles malformed documents better. Verify the specific package documentation and version before adopting it; the preceding examples provide documented alternatives for common parsing and extraction tasks.

Choose an HTML Parser

Use Beautiful Soup when you want a convenient navigable tree and straightforward element access. Choose PyQuery when CSS-style selection fits the task. Use lxml when XPath queries or its element-tree APIs suit your application. Use jusText when the goal is to identify likely main-text paragraphs rather than target known tags. These are task-based distinctions, not a performance ranking.

All four approaches operate on HTML content supplied to them. Keep network retrieval, response validation, and parsing as separate steps. For any selector, consider that the target may be absent, and check the extracted text against representative input from your own pages.

Conclusion

Python offers several ways to parse local HTML: Beautiful Soup and lxml expose element trees, PyQuery offers CSS-style selection, and jusText targets likely main text. Start with the output you need, pass the HTML explicitly, and verify results against the structure and language of your input.