BeautifulSoup4和 lxml 一样,Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据。
BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐使用lxml 解析器。
Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
1、安装
pip install beautifulsoup4
2、使用
from bs4 import BeautifulSoup#导入
soup = BeautifulSoup(html,"html.parser") #创建对象, 第一个参数是页面文本,第二个参数表示解析格式
3、 find 和 find_all
- find 和 find_all 可以有多个搜索条件叠加,比如find('a', id='link3', class_='sister',text=re.compile('link')) text可以用正则匹配
- find 返回的是一个bs4.element.Tag 对象,这个对象可以进一步进行搜索。如果有多个满足的结果,find只返回第一个;如果没有,返回 None。
- find_all 返回的是一个由 bs4.element.Tag 对象组成的 list,不管找到几个或是没找到,都是 list。
- find_all的简写,标签直接加括号
- find_all的其他参数
limit=2 # 限制只返回前两个,
recursive=False# 只查找子节点,不查找孙节点
from bs4 import BeautifulSoup
a = '''
<h1>标题1</h1>
<h2>标题2</h2>
<h2>标题3</h2>
<span>span111</span>
<span>span222</span>
<span>span333</span>
'''
soup = BeautifulSoup(a, "html.parser")
# 提取唯一标签的三种方法
soup.h1
soup.find('h1')
soup.find_all('h1')[0]
# 上面三条结果都是 <h1>标题1</h1>
soup.find_all('h2')
# [<h2>标题2</h2>, <h2>标题3</h2>]
soup.find_all(['h1','h2'])
# [<h1>标题1</h1>, <h2>标题2</h2>, <h2>标题3</h2>]
# 使用正则表达式
import re
soup.find_all(re.compile('^h'))
# [<h1>标题1</h1>, <h2>标题2</h2>, <h2>标题3</h2>]
#切片
soup.find_all('span')[-1].text[:-3]
#span
#-------------------------------------------------------------------------------------------------------------------------------
b = '''
<p id='p1'>段落1</p>
<p id='p2'>段落2</p>
<p class='p3'>段落3</p>
<p class='p3' id='pp'>段落4</p>
<span id="s">哒哒哒哒哒哒</span>
'''
soup1 = BeautifulSoup(b, "html.parser")
# 第一种,直接将属性名作为参数名,但是有些属性不行,比如像a-b这样的属性
soup1.find_all('p', id = 'p1') # 一般情况
soup1.find_all('p', class_='p3') # class是保留字比较特殊,需要后面加一个_
# 最通用的方法
soup1.find_all('p', attrs={'class':'p3'}) # 包含这个属性就算,而不是只有这个属性
soup1.find_all('p', attrs={'class':'p3','id':'pp'}) # 使用多个属性匹配
soup1.find_all('p', attrs={'class':'p3','id':False}) # 指定不能有某个属性
soup1.find_all('p', attrs={'id':['p1','p2']}) # 属性值是p1或p2
# 正则表达式匹配
import re
soup1.find_all('p', attrs={'id':re.compile('^p')}) # 使用正则表达式
soup1.find_all('p', attrs={'class':True}) # 含有class属性即可
# find_all的简写,标签直接加括号
soup.span('span',id='s') # 相当于调用find_all返回list
# find_all的其他参数
soup.find_all('span', limit=2) # 限制只返回前两个
soup.find_all('span', recursive=False) # 只查找子节点,不查找孙节点
5、 根据标签内内容来识别
from bs4 import BeautifulSoup
a = '''
<p id='p1'>段落1</p>
<p class='p3'>段落2</p>
<p class='p3'>文章</p>
<p></p>
'''
soup = BeautifulSoup(a, "html.parser")
soup.find_all('p', text='文章')
soup.find_all('p', text=['段落1','段落2'])
# 正则表达式
import re
soup.find_all('p', text=re.compile('段落'))
soup.find_all('p',text=True)
# 传入函数
def nothing(c):
return c not in ['段落1','段落2','文章']
soup.find_all('p',text=nothing)
# 同上
def nothing(c):
return c is None
soup.find_all('p',text=nothing)
函数的使用在attr中也可以
a = '''
<p id='p1'>段落1</p>
<p id='p2'>段落2</p>
<p class='p3'>段落3</p>
<p class='p3' id='pp'>段落4</p>
'''
soup = BeautifulSoup(a, "html.parser")
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
print(soup.find_all(has_class_but_no_id)) # 函数的参数应该是标签
#[<p class="p3">段落3</p>]
def nothing(c):
return c not in ['p2']
print(soup.find_all('p', id=nothing))
#[<p id="p1">段落1</p>, <p class="p3">段落3</p>, <p class="p3" id="pp">段落4</p>]
6、 提取内容
- 提取标签内容:使用.text
- 提取标签属性值,像字典一样提取
a = '''
<body>
<h><a href='www.biaoti.com'>标题</a></h>
<p>段落1</p>
<p>段落2</p>
</body>
'''
soup = BeautifulSoup(a, 'html.parser')
# 提取内容
soup.p.text
for p in soup.find_all('p'):
print(p.text)
soup.h.text # 多层嵌套也可以直接返回
soup.h.a.text # 也可以这样
soup.body.text # 里面有多个内容时 '\n标题\n段落1\n段落2\n'
# 提取属性值,像字典一样提取,以下两种方法等价
soup.h.a['href']
soup.h.a.get('href')
4.2、.string和.get_text()区别
- .string:只是获取该标签内部的文本,不包括子标签内的文本/****
-
.get_text():获取标签内所有****文本,包括所有子标签内的文本**
7、 查看标签信息
- 获得标签名
- 获得标签所有属性的字典
- 检查标签是否有某属性
a = '''
<body>
<h><a href='www.biaoti.com'>标题</a></h>
<p>段落1</p>
<p></p>
</body>
'''
soup = BeautifulSoup(a, 'html.parser')
for i in soup.body.find_all(True):
print(i.name) # 提取标签名
print(i.attrs) # 提取标签所有属性值
print(i.has_attr('href')) # 检查标签是否有某属性
4.4 select CSS选择器