python网络爬虫——编码

输出

格式化输出
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()来指定编码格式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值