要获取完整的HTML代码,可以使用Beautiful Soup库中的prettify()方法。该方法返回整个HTML文档的Unicode字符串,包括标签、属性和内容。
下面是一个示例代码:
from bs4 import BeautifulSoup
html = """
Beautiful Soup Demo
Hello, Beautiful Soup!
This is a demo page for Beautiful Soup.
"""
soup = BeautifulSoup(html, 'html.parser')
full_html = soup.prettify()
print(full_html)
输出结果:
Beautiful Soup Demo
Hello, Beautiful Soup!
This is a demo page for Beautiful Soup.
通过调用prettify()方法,我们可以获取完整的HTML代码,包括缩进和换行符。