3.2 Beautiful Soup的使用(借助网页的结构和属性等特性来解析网页)
3.2.1 Beautiful Soup的简介
(1)概述
Beautiful Soup是Python的一个HTML或XML的解析库,用它可以方便地从网页中提取数据。
(2)功能及应用
Beautiful Soup提供一些简单的、Python式的函数来处理导航、搜索、修改分析树等功能。
(3)特点
作为一个工具箱,通过解析文档为用户提供需要抓取的数据,无须很多代码就可以写出一个完整的应用程序。
Beautiful Soup自动将输入文档转换为Unicode编码,将输出文档转换为utf-8编码。不需要考虑编码方式。
Beautiful Soup已成为和Ixml、html5lib一样出色的Python解释器。
3.2.2 解析器
BeautifulSoup在解析时依赖解析器,它除了支持Python标准库中的HTML解析器,还支持一些第三方解析器(例如lxml)。
使用LXML解析器,只需在初始化Beautiful Soup时,把第二个参数改为1xml即可,如:
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>Hello</p>','lxml')
print(soup.p.string)
3.2.3 准备工作
开始之前,安装好Beautiful Soup和lxml这两个库。Beautiful Soup直接使用pip3安装即可,命令如下:
pip3 install beautifulsoup4;Mac:!pip install beautifulsoup4

3.2.4 基本使用
例3.2 先通过实例看看Beautiful Soup的基本用法:
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>
"""
from bs4 import BeautifulSoup
soup =BeautifulSoup(html,'lxml')
print(soup.prettify())
print(soup.title.string)
结果如下:

说明:首先声明一个变量html,是一个HTML字符串。
接着,将它当作第一个参数传给BeautifulSoup对象,该对象的第二个参数为解析器的类型(这里使用1xml),此时就完成了BeaufulSoup对象的初始化。
然后,将这个对象赋值给soup变量。
之后就可以调用soup的各个方法和属性解析这串HTML代码了。
首先,调用prettify方法。这个方法可以把要解析的字符串以标准的缩进格式输出。需要注意的是,输出结果里包含body和html节点,也就是说对于不标准的HTML字符串BeautifulSoup,可以自动更正格式。
然后,调用soup.title.string,这实际上是输出HTML中title节点的文本内容。
总而言之,通过soup.title选出HTML中的title节点,再调用string属性就可以得到title节点里面的文本了。
3.2.5 节点选择器
(1)原理
直接调用节点的名称即可选择节点,然后调用string属性就可以得到节点内的文本了。这种选择方式速度非常快,当单个节点结构层次非常清晰时,可以选用这种方式来解析。
(2)实例
用一个例子详细说明选择节点的方法:
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">0nce 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>
"""
from bs4 import BeautifulSoup
soup =BeautifulSoup(html,'lxml')
print(soup.title)
print(type(soup.title))
print(soup.title.string)
print(soup.head)
print(soup.p)
结果如下:

说明:使用刚才的HTML代码,首先打印出title节点的选择结果,输出结果正是title节点及里面的文字内容。
接下来,输出title节点的类型,是bs4.element.Tag,这是Beautiful Soup中一个重要的数据结构,经过选择器选择的结果都是这种Tag类型。Tag具有一些属性,例如string属性,调用该属性可以得到节点的文本内容,所以类型的输出结果正是节点的文本内容。
输出文本内容后,又尝试选择了head节点,结果是节点加其内部

最低0.47元/天 解锁文章


被折叠的 条评论
为什么被折叠?



