和 lxml 一样,Beautiful Soup 也是一个 HTML/XML 解析库,主要功能也是解析和提取 HTML/XML 数据。
lxml 只会局部遍历,而 Beautiful Soup 是基于 HTML DOM 的,会载入整个文档,解析整个 DOM 树,因此时间和内存的开销都会大很多,所以性能要低于 lxml 。
BeautifulSoup 用来解析 html 比较简单,API 非常人性化,支持 CSS 选择器、Python 标准库中的 HTML 解析器,也支持 lxml 的 XML 解析器。
Beautiful Soup 3 目前已停止开发,推荐现在的项目使用 Beautiful Soup 4。
- 安装
pip install bs4
几大解析工具对比
解析工具 | 解析速度 | 使用难度 |
---|---|---|
BeautifulSoup | 最慢 | 最简单 |
lxml | 快 | 简单 |
正则表达式 | 最快 | 最难 |
简单使用
from bs4 import BeautifulSoup
html = '''
<html>
<head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dormouse"><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>
</body
</html>
'''
# 创建 BeautifulSoup 对象
# 使用 lxml 来解析
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())
关于BeautifulSoup 的解析引擎(Parser) ,下面是摘自官方文档的截图:
常用方法及使用示例
- find_all 的使用:
1.在提取标签时,第一个参数是标签的名字。然后如果在提取标签的时候想要使用标签属性进行过滤,那么可以在这个方法中通过关键字参数的形式,将属性的名字以及对应的值传进去。或者是使用 attrs
属性,将所有属性以及对应的值放在一个字典中传给 attrs
属性。
2.有些时候,在提取标签时不想提取那么多,那么可以使用 limit
参数,限制提取个数。
- find 和 find_all 的区别:
1.find
2.find_all
- 示例代码:
from bs4 import BeautifulSoup
html = '''
...
'''
soup = BeautifulSoup(html, 'lxml')
# 1.获取所有的 tr 标签
trs = soup.find_all('tr')
for tr in trs:
print(tr)
# 2.获取第二个 tr 标签
tr = soup.find_all('tr', limit=2)[1]
print(tr)
# 3.获取所有 class 等于 even 的 tr 标签
trs = soup.find_all('tr',attrs={'class':'even'}) # 或者用键值对的方式:class_=even
for tr in trs:
print(tr)
# 4.将所有 id 等于 test, class 也等于 test 的 a 标签提取出来
aList = soup.find_all('a', attrs={'id':'test', 'class':'test'}) # 或者:id='test', class_='test'
for a in aList:
print(a)
# 5.获取所有 a 标签的 href 属性
aList = soup.find_all('a')
for a in aList:
# 获取属性的方式一:通过下标操作
href = a['href']
print(href)
# 获取属性的方式二:通过 attrs 属性的方式
# href = a.attrs['href']
# print(href)
# 6.获取所有的职位信息(纯文本)
trs = soup.find_all('tr')[1:]
for tr in trs:
# 方式一
# tds = tr.find_all('td')
# title = tds[0].string
# category = tds[1].string
# nums = tds[2].string
# city = tds[3].string
# pubtime = tds[4].string
# 方式二
# infos = tr.strings
infos = tr.stripped_strings # stripped_string 获取的是不包含非空白的字符(包括换行等)
for info in infos:
print(info)
未完待续。。。