回顾
上一次介绍正则表达式的时候,分享了一个爬虫实战,即爬取豆瓣首页所有的:书籍、链接、作者、出版日期等。在上个实战中我们是通过正则表达式来解析源码爬取数据,整体来说上次实战中的正则表达式是比较复杂的,所以引入了今天的主角BeautifulSoup:它是灵活方便的网页解析库,处理高效,而且支持多种解析器。使用Beautifulsoup,不用编写正则表达式就可以方便的实现网页信息的提取。
一、 BeautifulSoup的安装
pip install beautifulsoup4
二、用法讲解
1. 解析库
解析器 | 使用方法 | 优势 | 劣势 |
---|---|---|---|
Python标准库 | BeautifulSoup(markup, “html.parser”) | Python的内置标准库、执行速度适中 、文档容错能力强 | Python 2.7.3 or 3.2.2)前的版本中文容错能力差 |
lxml HTML 解析器 | BeautifulSoup(markup, “lxml”) | 速度快、文档容错能力强,常用 | 需要安装C语言库 lxml |
lxml XML 解析器 | BeautifulSoup(markup, “xml”) | 速度快、唯一支持XML的解析器 | 需要安装C语言库 |
html5lib | BeautifulSoup(markup, “html5lib”) | 最好的容错性、以浏览器的方式解析文档、生成HTML5格式的文档 | 速度慢、不依赖外部扩展 |
2.基本使用
下面是一个不完整的html:body标签、html标签都没有闭合
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
下面使用lxml解析库解析上面的html
from bs4 import BeautifulSoup#引包
soup = BeautifulSoup(html, 'lxml')#声明bs对象和解析器
print(soup.prettify())#格式化代码,自动补全代码,进行容错的处理
print(soup.title.string)#打印出title标签中的内容
下面是容错处理时标签补全后的结果和获取的title内容,可以看到html和body标签都被补全了:
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
<body>
<p class="title" name="dromouse">
<b>
The Dormouse's story
</b>
</p >
<p class="story">
Once upon a time there were three little sisters; and their names were
<a class="sister" href=" " id="link1">
<!-- Elsie -->
</ a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</ a>
and
<a class="sister" href="http://example.com/tillie" id="link3