首页 > 其他 > 详细

关于BeautifulSoup4 解析器的说明

时间:2019-06-20 10:22:37      阅读:98      评论:0      收藏:0      [点我收藏+]

一.解析器概述

  如同前几章笔记,当我们输入:

soup=BeautifulSoup(response.body)

  对网页进行析取时,并未规定解析器,此时使用的是python内部默认的解析器“html.parser”。

  解析器是什么呢? BeautifulSoup做的工作就是对html标签进行解释和分类,不同的解析器对相同html标签会做出不同解释。

  举个官方文档上的例子:

BeautifulSoup("<a></p>", "lxml")
# <html><body><a></a></body></html>
BeautifulSoup("<a></p>", "html5lib")
# <html><head></head><body><a><p></p></a></body></html>
BeautifulSoup("<a></p>", "html.parser")
# <a></a>

  官方文档上多次提到推荐使用"lxml"和"html5lib"解析器,因为默认的"html.parser"自动补全标签的功能很差,经常会出问题。

 

二.不同解析器的对比

Parser Typical usage Advantages Disadvantages
Python’s html.parser BeautifulSoup(markup, "html.parser")
  • Batteries included
  • Decent speed
  • Lenient (as of Python 2.7.3 and 3.2.)
  • Not very lenient (before Python 2.7.3 or 3.2.2)
lxml’s HTML parser BeautifulSoup(markup, "lxml")
  • Very fast
  • Lenient
  • External C dependency
lxml’s XML parser BeautifulSoup(markup, "lxml-xml") BeautifulSoup(markup,"xml")
  • Very fast
  • The only currently supported XML parser
  • External C dependency
html5lib BeautifulSoup(markup, "html5lib")
  • Extremely lenient
  • Parses pages the same way a web browser does
  • Creates valid HTML5
  • Very slow
  • External Python dependency

  可以看出,“lxml”的解析速度非常快,对错误也有一定的容忍性。“html5lib”对错误的容忍度是最高的,而且一定能解析出合法的html5代码,但速度很慢。

  我在实际爬取网站的时候,原网页的编码方式不统一,其中有一句乱码,用“html.parser”和“lxml”都解析到乱码的那句,后面的所有标签都被忽略了。而“html5lib”能够完美解决这个问题。

 

三.from_encoding参数 (对应BeautifulSoup3中的fromEncoding参数)

  由于不同网站的编码方式不同,在用BeautifulSoup进行解析时,要注明对应的编码方式。

  查看编码方式的方法如下:  

import chardet
chardet.detect(response.body)

  如:得到

{‘confidence‘: 0.99, ‘encoding‘: ‘GB2312‘}

  由此可知编码方式为GB2312,在析取时,默认的from_encoding参数为utf-8,不是utf-8的应注明。即:

soup=BeautifulSoup(respone.body,"html5lib",from_encoding=‘gb2312‘)

 

转载:https://www.cnblogs.com/KoalaDream/p/4706316.html

关于BeautifulSoup4 解析器的说明

原文:https://www.cnblogs.com/hls91/p/11056791.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!