Beautiful Soup

3.2.2 · maintenance · verified Wed Apr 15

Beautiful Soup (version 3.x) is a Python 2 library for parsing HTML and XML documents, including those with malformed markup. It creates a parse tree that can be used to extract data from web pages, making it useful for screen-scraping tasks. Version 3.2.2 is the final release in this series. Development on the 3.x series ended in 2011, and it has been largely superseded by `beautifulsoup4` for Python 3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic HTML parsing and element extraction using Beautiful Soup 3.x. It creates a `BeautifulSoup` object from an HTML string and then accesses elements by tag name and attributes. Note that Beautiful Soup 3.x does not take an explicit parser argument like `html.parser` which is common in Beautiful Soup 4.x.

from BeautifulSoup import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
</body></html>
"""

# For Beautiful Soup 3.x, you pass the HTML string directly.
# It defaults to Python's SGMLParser.
soup = BeautifulSoup(html_doc)

print("Document Title:", soup.title.string)
print("First paragraph's class attribute:", soup.p['class'])
print("First anchor tag (link):", soup.a)
print("Text of the first link:", soup.a.string)

view raw JSON →