Prettify and Output Formatting
Parsed documents usually come out as one long line of HTML. .prettify() re-serializes the tree with indentation so you can read and debug it, and the other output methods give you control over the final format.
.prettify()
from bs4 import BeautifulSoup
html = "<html><body><h1>T</h1><ul><li>a</li><li>b</li></ul></body></html>"
soup = BeautifulSoup(html, "html.parser")
print(soup.prettify())
# <html>
# <body>
# <h1>
# T
# </h1>
# <ul>
# <li>
# a
# </li>
# ...
prettify() re-indents the whole tree and is the fastest way to inspect what the parser actually did with your input.
Writing Output Files
Write the prettified (or modified) tree to a file. Bytes mode with .encode() preserves the encoding:
with open("pretty.html", "wb") as f:
f.write(soup.prettify().encode("utf-8"))
XML Output
If you parsed with lxml, you can emit the document back as XML, keeping or dropping the declaration:
xml = "<?xml version="1.0"?><root><a/></root>"
soup = BeautifulSoup(xml, "lxml")
print(soup.prettify()) # XML with declaration preserved
Tips
- prettify() adds whitespace that was not in the original; never feed the output back as data if whitespace matters.
- For compact machine output, str(tag) or tag.decode() avoids re-indentation.
- Diffing two prettified documents is a decent smoke test that a transform changed only what you intended.
Summary
prettify() re-serializes the parse tree with indentation for debugging and human reading; write it with encode() to keep encoding under control. Use str(tag) or decode() for compact markup output, and lxml-parsed documents can be emitted back as XML with the declaration intact.