解析库就是在爬虫时自己制定一个规则,帮助我们抓取想要的内容时用的。常用的解析库有re模块的正则、beautifulsoup、pyquery等等。正则完全可以帮我们匹配到我们想要住区的内容,但正则比较麻烦,所以这里我们会用beautifulsoup。
beautifulsoup
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库。它能够通过你喜欢的转换器实现惯用的文档导航、查找、修改文档的方式。Beautiful Soup会帮我们节省数小时甚至数天的工作时间。Beautiful Soup 3 目前已经停止开发,官网推荐在现在的项目中使用Beautiful Soup 4。
安装:
pip install beautifulsoup4
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器。其中一个是 lxml 。我们平常在使用中推荐使用lxml。另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,
pip install lxml pip install html5lib
下表列出了主要的解析器,以及它们的优缺点,官网推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定.
| 解析器 | 使用方法 | 优势 | 劣势 |
|---|---|---|---|
| Python标准库 | BeautifulSoup(markup, "html.parser") |
|
|
| lxml HTML 解析器 | BeautifulSoup(markup, "lxml") |
|
|
| lxml XML 解析器 |
BeautifulSoup(markup, ["lxml", "xml"]) BeautifulSoup(markup, "xml") |
|
|
| html5lib | BeautifulSoup(markup, "html5lib") |
|
|
中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
基本使用
容错处理:BeautifulSoup文档的容错能力指的是在html代码不完整的情况下,使用该模块可以识别该错误。使用BeautifulSoup解析某些没写完整标签的代码会自动补全该闭合标签,得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出。
举个栗子:
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" >Elsie</a>, <a href="http://example.com/lacie" class="sister" >Lacie</a> and <a href="http://example.com/tillie" class="sister" >Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ from bs4 import BeautifulSoup soup=BeautifulSoup(html_doc,'lxml') #具有容错功能,第二个参数是解析器名,这里我们确定用lxml res=soup.prettify() #处理好缩进,结构化显示 print(res)