Last modified: Aug 20, 2023 By Alexander Williams

How to use Beautifulsoup prettify

The prettify() method is one of Beautiful Soup's features. It is used to make the results look better. In this tutorial, we'll learn how to use this method with examples.

.prettify() syntax

Here is the syntax of the .prettify():

  • soup: is the BeautifulSoup object with parsed HTML/XML.
  • .prettify(): is the BeautifulSoup object method that prettifies parsed content.

How to use .prettify()

Here is an example of how to use the prettify() method:

from bs4 import BeautifulSoup

# HTML content
html = "<html><head><title>Sample Page</title></head><body><h1>Hello, World!</h1><p>This is a sample paragraph.</p></body></html>"

# Create a BeautifulSoup object by parsing the HTML content
soup = BeautifulSoup(html, 'html.parser')

# Prettify the parsed HTML
prettified_html = soup.prettify()

# Print the prettify formatted HTML


   Sample Page
   Hello, World!
   This is a sample paragraph.

As you can see, the HTML result structure looks clear and understandable.


You just saw the steps on how to use the Beautiful Soup prettify() method to make the HTML result structure clear and understandable.