- 开启BeautifulSoup之旅
在使用之前,我们还需要配置解析器,本文及之后都使用python自带的解析器”html.parser”,更多解析器介绍及比较可参考本人博客 Beautiful Soup4 之table数据提取。我们使用一个最常见的例子来说明其使用方法:
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" 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>
"""
使用BeautifulSoup来解析这段代码:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
首先引入库函数,接着我们声明一个Beautifulsoup对象soup,括号内的两个参数分别是要解析的代码段、使用的解析器,以后我们还将丰富参数,如在此配置编码等,暂时我们只需要这两个参数即可。接下来仅需对这个对象进行操作即可。
#示例1
soup.title
# <title>The Dormouse's story</title>
#示例2
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
#示例3
soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
以上代码分别是解析代码,获取解析对象的title标签内容、a标签内容、获取所有a标签内容,这就是最简单的应用啦!当然有可能有的小伙伴会疑惑,示例2和示例3都是获取a标签,为什么结果这么大差异呢?这就涉及到对象的种类及相关的属性、操作方法。
2.对象
- Tag
Tag 对象与XML或HTML原生文档中的tag相同,其最重要的属性为:name和attributes - NavigableString
Beautiful Soup用 NavigableString 类来包装tag中的字符串,一个 NavigableString 字符串与Python中的Unicode字符串相同。 - BeautifulSoup
BeautifulSoup 对象表示的是一个文档的全部内容 - Comment
Comment 对象是一个特殊类型的 NavigableString 对象
更多有关对象的介绍及使用等可在官方文档内获取,本文不做过多总结,用到哪说到哪。