是的,你可以使用BeautifulSoup的prettify()方法来对HTML代码进行美化。该方法会自动添加缩进和换行符,使HTML代码更易读。
以下是一个示例代码,演示了如何使用prettify()方法对HTML代码进行美化:
from bs4 import BeautifulSoup
html = '''
BeautifulSoup Example
Welcome to BeautifulSoup Example
This is a paragraph.
This is another paragraph.
'''
soup = BeautifulSoup(html, 'html.parser')
pretty_html = soup.prettify()
print(pretty_html)
运行以上代码,将输出美化后的HTML代码:
BeautifulSoup Example
Welcome to BeautifulSoup Example
This is a paragraph.
This is another paragraph.
如你所见,prettify()方法会在适当的位置添加缩进和换行符,使HTML代码更易读。注意,这并不会改变原始HTML代码的结构,只是在输出时进行了美化。