Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Pretty Print HTML In Python With BeautifulSoup

Code

from bs4 import BeautifulSoup as bs

input = """<html><head><title>
Pretty Print Example</title>
</head><body><p>Alfa Bravo Charlie</p>
</body></html>"""

soup = bs(input)

pretty_html = soup.prettify()

print(pretty_html)

Results

<html>
 <head>
  <title>
   Pretty Print Example
  </title>
 </head>
 <body>
  <p>
   Alfa Bravo Charlie
  </p>
 </body>
</html>