Pretty print

prettify messy HTML the parser repaired.

html.parser repairs unclosed tags. prettify() prints the repaired tree with indentation so you can see what the parser decided.

Goal

Parse messy markup, print it raw vs pretty.

Repair

html = """
<p>Unclosed paragraph
<ul>
<li>Nairobi
<li>Mombasa
</ul>
"""
soup = BeautifulSoup(html, "html.parser")
print("--- str ---")
print(soup)
print("--- pretty ---")
print(soup.prettify())

The parser closes the <p> and each <li>. Pretty output is for reading, not for byte-stable diffs.

Encode

html = "<p>Kisumu</p>"
soup = BeautifulSoup(html, "html.parser")
print(str(soup))
print(soup.encode("utf-8"))

str(soup) is the compact HTML string. Use that when you write a file.

Tip

Attach messy.html from the banner and pretty-print it in the Files chapter.