输出
格式化输出
prettify()方法将BeautifulSoup的文档格式化后以unicode编码输出,每个XML/HTML标签都独占一行。
markup='<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup=BeautifulSoup(markup)
print soup.prettify()
"""
<html>
<body>
<a href="http://example.com/">
I linked to
<i>
example.com
</i>
</a>
</body>
</html>
"""
BeautifilSoup对象和它的tag节点都可以调用prettify()方法:
print soup.a.prettify()
"""
<a href="http://example.com/">
I linked to
<i>
example.com
</i>
</a>
"""
压缩输出
如果只想得到结果字符串,不注重格式。那么可以对一个BeautifulSoup对象或者Tag对象使用Python的unicode()或str()方法:
print str(soup)
# <html><body><a href="http://example.com/">I linked to <i>example.com</i></a></body></html>
print unicode(soup.a)
# <a href="http://example.com/">I linked to <i>example.com</i></a>
输出格式
BeautifulSoup输出是会将HTML种的特殊字符转换成Unicode;
编码
任何HTML或XML文档都有自己的编码方式,但解析后文档都被转换成Unicode:
markup="<h1>Sacr\xc3\xa9 bleu!</h1>"
soup=BeautifulSoup(markup)
print soup.h1
# <h1>Sacré bleu!</h1>
BeautifulSoup永乐编码自动检测自测来识别当前文档编码并转换成Unicode编码。
print soup.original_encoding
# utf-8
如果预先知道文档编码,可以设置编码参数来减少自动检查编码出错概率并且提高文档解析速度。
markup = b"<h1>\xed\xe5\xec\xf9</h1>"
soup=BeautifulSoup(markup)
print soup.h1
# <h1>íåìù</h1>
#误判断为windows-1252
print soup.original_encoding
# windows-1252
#指定编码格式
soup=BeautifulSoup(markup,from_encoding='iso-8859-8')
print soup.h1
# <h1>םולש</h1>
输出编码
如果不想用UTF-8编码输出,可以将编码方式传入 prettify() 方法,或者encode()来指定编码格式。