要在BeautifulSoup解析的HTML文档中的每个开标签和闭标签之前和之后添加额外的空格,可以使用prettify()方法。prettify()方法将HTML文档转换为格式化后的字符串,并在每个标签前后添加了额外的空格。
下面是一个示例代码:
from bs4 import BeautifulSoup
html = '''
Example
Hello, World!
This is an example.
'''
soup = BeautifulSoup(html, 'html.parser')
formatted_html = soup.prettify()
print(formatted_html)
运行以上代码会输出格式化后的HTML文档,并在每个标签前后添加了额外的空格:
Example
Hello, World!
This is an example.
如上所示,通过使用prettify()方法,我们可以在每个标签之前和之后添加额外的空格,以使HTML文档更易读。