爬虫解析库之bs4模块详解

06.爬虫解析库之bs4

 

文章目录

  • 06.爬虫解析库之bs4
    • 一、介绍
      • 1.基本介绍
      • 2.html中搜索数据的时候三种方式
      • 3.安装
      • 4.解析器
    • 二、基本使用
    • 三、遍历文档树
      • 1.介绍
      • 2.用法 遍历
      • 3.获取标签的名称
      • 4.获取标签的属性(如果是class就放到列表中)
      • 5.获取标签的内容
      • 6.嵌套选择
      • 7.子节点、子孙节点(了解)
      • 8.父节点、祖先节点(了解)
      • 9.兄弟节点(了解)
      • 11.小结
    • 四、bs4之搜索文档树
      • 1.五种过滤器:字符串、正则表达式、列表、布尔值、方法
        • 字符串
        • 正则表达式
        • 列表
        • 布尔
        • 方法(了解)
        • 小结
      • 2.其他
      • 3. find_all
      • 4.find
      • 5.其他方法
      • 6.CSS选择器
      • 7. 修改文档树
      • 8. 通用性

 

一、介绍

1.基本介绍

  • Beautiful Soup 3 目前已经停止开发,官网推荐在现在的项目中使用Beautiful Soup 4, 移植到BS4
  • Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库
  • 默认有个解析器:html.parser
  • 也可以额外安装:lxml

2.html中搜索数据的时候三种方式

  • css选择器 (通用)
  • xpath选择器 (通用)
  • 模块提供的查找方法(find,find_all)

3.安装

# 安装 Beautiful Soup
pip install beautifulsoup4

# 安装解析器
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操作系统不同,可以选择下列方法来安装lxml:

$ apt-get install Python-lxml

$ easy_install lxml

$ pip install lxml

另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:

$ apt-get install Python-html5lib

$ easy_install html5lib

$ pip install html5lib

4.解析器

下表列出了主要的解析器,以及它们的优缺点,官网推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定.

解析器 使用方法 优势 劣势
Python标准库 BeautifulSoup(markup, "html.parser") Python的内置标准库执行速度适中文档容错能力强 Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml HTML 解析器 BeautifulSoup(markup, "lxml") 速度快文档容错能力强 需要安装C语言库
lxml XML 解析器 BeautifulSoup(markup, ["lxml", "xml"])``BeautifulSoup(markup, "xml") 速度快唯一支持XML的解析器 需要安装C语言库
html5lib BeautifulSoup(markup, "html5lib") 最好的容错性以浏览器的方式解析文档生成HTML5格式的文档 速度慢不依赖外部扩展

中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

二、基本使用

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title">zhangchengDSB <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 item" 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

# BeautifulSoup(markup=html_doc, features='html.parser')
soup = BeautifulSoup(markup=html_doc, features='lxml')

# 处理好缩进,结构化显示,美化
res = soup.prettify()  # /ˈprɪtɪfaɪ/
print(res)
'''
<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
 <body>
  <p class="title">
   zhangchengDSB
   <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 item" href="http://example.com/elsie" 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">
    Tillie
   </a>
   ;
and they lived at the bottom of a well.
  </p>
  <p class="story">
   ...
  </p>
 </body>
</html>
'''

三、遍历文档树

1.介绍

# 优势: 直接通过标签名字选择,特点是选择速度快
# 缺点: 如果存在多个相同的标签则只返回第一个

# 1、用法
# 2、获取标签的名称
# 3、获取标签的属性
# 4、获取标签的内容
# 5、嵌套选择
# 6、子节点、子孙节点
# 7、父节点、祖先节点
# 8、兄弟节点

2.用法 遍历

# bs4.element.Tag   每个标签对象,用起来跟soup对象一样用
print(soup.html.head)
print(soup.html.body.p)

3.获取标签的名称

# bs4.element.Tag  有一个name属性
print(soup.html.body.name)  #body

4.获取标签的属性(如果是class就放到列表中)

print(soup.html.body.p)
print(soup.html.body.p.attrs)
print(soup.html.body.p.attrs.get('class'))
print(soup.html.body.p.attrs['id'])
print(soup.html.body.p['class'])  #如果是class就放到列表中
print(soup.html.body.p['id'])  #id是一个

'''
<p class="title" id="id_p">p的内容<b>The Dormouse's story<span>孙子</span></b><span>lqz</span></p>
{'class': ['title'], 'id': 'id_p'}
['title']
id_p
['title']
id_p
'''

5.获取标签的内容

print(soup.html.body.p)
print(soup.html.body.p.text)  #获取该标签子子孙孙的文本内容

print(soup.html.body.p.string)  #这个标签必须没有子孙,才能拿出文本内容

print(list(soup.html.body.p.strings))  #把子子孙孙的文本内容放到一个生成器中

'''
<p class="title" id="id_p">p的内容<b>The Dormouse's story<span>孙子</span></b><span>lqz</span></p>
p的内容The Dormouse's story孙子lqz
None
['p的内容', "The Dormouse's story", '孙子', 'lqz']
'''

6.嵌套选择

print(soup.p.b.string)

7.子节点、子孙节点(了解)

print(soup.p.contents) #p下所有子节点

print(soup.p.children) #得到一个迭代器,包含p下所有子节点
for i,child in enumerate(soup.p.children):
    print(i,child)

print(soup.p.descendants) #获取子孙节点,p下所有的标签都会选择出来
for i,child in enumerate(soup.p.descendants):
    print(i,child)

8.父节点、祖先节点(了解)

print(soup.b.parent) #获取b标签的父节点
print(list(soup.b.parents)) #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...
print(len(list(soup.b.parents))) #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...

9.兄弟节点(了解)

print(soup.a.next_sibling) #紧邻的下一个兄弟(如果是空格就会拿出空格)
print(soup.a.previous_sibling) #上一个兄弟

print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
print(soup.a.previous_siblings) #上面的兄弟们=>生成器对象

11.小结

# 注意: 多个标签结果之返回一条
soup.head             获取标签(多条中的第一条) 

soup.head.name        获取标签名称 

soup.head.attrs       获取标签属性 {'class': [xx, yy, ...], 'id': jj}

soup.text             获取标签下所有的文本内容
soup.string           获取标签下只有一个文本内容存在的文本内容 
soup.strings          获取标签下所有文本内容, 制作成一个迭代器对象

soup.get('属性名')     获取标签中的属性值

soup.contents         获取标签下所有子节点 (注意: 包含空格等符号)
soup.children         获取标签下所有所有子节点, 制作成迭代器

soup.parent           获取标签的父节点(单个)
soup.parents          获取标签的所有祖先节点

soup.next_sibling     获取标签的下一个兄弟 (提示: 逗号也被涵盖了, 不好用)
soup.previous_sibling 获取标签的上一个兄弟 (提示: 空格也被涵盖了, 也不好用)

四、bs4之搜索文档树

1.五种过滤器:字符串、正则表达式、列表、布尔值、方法

  • soup.find() :找到符合的第一个(提示: 内部本质还是调用了 find_all()[0])
  • soup.find_all() :找到符合的所有

字符串

# 遍历文档树

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p'>p的内容<b>The Dormouse's story<span>孙子</span></b><span>lqz</span></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" xx='xx'><span>lqz</span>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" name='lqz'>Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc, 'lxml')
res=soup.find(name='body',)
# 找a标签,id为 link1
res=soup.find(name='a',id='link1')
res=soup.find_all(name='a',class_='sister')
res=soup.find_all(name='a',href="http://example.com/elsie")
res=soup.find_all(name='a',xx='xx')

res=soup.find_all(name='a',attrs={'class':'sister'})   # 以属性找attrs
res=soup.find_all(attrs={'id':'link1'})
res=soup.find_all(attrs={'xx':'xx'})


res=soup.find_all(name='a',attrs={'name':'lqz'})
print(res)

正则表达式

import re
res=soup.find_all(name=re.compile('^b'))
res=soup.find_all(class_=re.compile('^s'))
res=soup.find_all(attrs={'name':'lqz'},id=re.compile('^l'))
print(res)

列表

res=soup.find_all(name=['b',])
res=soup.find_all(id=['link1','link2'])
print(res)

布尔

res = soup.find_all(class_=True)  # 有标签标签

res = soup.find_all(href=True)  # 有标签标签
print(res)

方法(了解)

  • 如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数
  • 如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
# 获取有类名,但是没有id的标签
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')


res = soup.find_all(name=has_class_but_no_id)
print(res)

小结

# 字符串
soup.find('a')     获取标签下第一个a标签
soup.find_all('a') 获取标签下所有的a标签
    
# 正则表达式
import re
pattern = re.compile(r'正则')
soup.find_all(name=pattern)

# 列表
soup.find_all(name=['b', 'a'])

# 布尔
soup.find_all(id=True)
soup.find_all(href=True)

# 方法
soup.find_all(has_class_but_no_id)

2.其他

# 遍历文档树和搜索文档树可以连用
res=soup.find(name='a').span.text
res=soup.html.body.find('a')
print(res)

# limit  限制取几条
soup.findChild()
res=soup.find_all(name='a',limit=1)
print(res)

# recursive 是否递归查找,如果是False是只找一层
res=soup.body.find_all(name='p',recursive=False)
res=soup.find_all(name='p',recursive=False)
res=soup.find_all(name='p',recursive=True)
print(res)

3. find_all

find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)

import re

# 1. name: 搜索name参数的值可以使任一类型的 过滤器 ,字符窜,正则表达式,列表,方法或是 True .
print(soup.find_all(name=re.compile('^t')))

# 2. keyword: key=value的形式,value可以是过滤器:字符串 , 正则表达式 , 列表, True .
print(soup.find_all(id=re.compile('my')))
print(soup.find_all(href=re.compile('lacie'), id=re.compile('\d')))  # 注意类要用class_
print(soup.find_all(id=True))  # 查找有id属性的标签

# 有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性:
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>', 'lxml')
# data_soup.find_all(data-foo="value") #报错:SyntaxError: keyword can't be an expression
# 但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag:
print(data_soup.find_all(attrs={"data-foo": "value"}))
# [<div data-foo="value">foo!</div>]

# 3. 按照类名查找,注意关键字是class_,class_=value,value可以是五种选择器之一
'''
print(soup.find_all('a', class_='sister'))  # 查找类为sister的a标签
print(soup.find_all('a', class_='sister ssss'))  # 查找类为sister和sss的a标签,顺序错误也匹配不成功
print(soup.find_all(class_=re.compile('^sis')))  # 查找类为sister的所有标签
'''

# 4. attrs
print(soup.find_all('p', attrs={'class': 'story'}))

# 5. text: 值可以是:字符,列表,True,正则
print(soup.find_all(text='Elsie'))
print(soup.find_all('a', text='Elsie'))

# 6. limit参数:如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果
print(soup.find_all('a', limit=2))
'''
[
    <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, 
    <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
]
'''

# 7. recursive: 调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .
print(soup.html.find_all('a'))
'''
[
    <a class="sister item" 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>
]
'''
print(soup.html.find_all('a', recursive=False))  # []

小结

# 参数: 
    def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
        """
        :param name: 标签名称上的过滤器。
        :param attrs: 属性值的过滤器字典。
        :param recursive: 属性值的过滤器字典。参数递归:如果为真,find_all()将执行递归搜索这个PageElement的子元素。否则,只有直接子女将被考虑。
        :param limit: 如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果
        :kwargs: 属性值的过滤器字典。
        :return: pageelement的结果集。
        """

# 拓展: 等价代码
    soup('a')
    soup.find('a')

    soup.p.find_all(text=True)
    soup.p(text=True)

4.find

find(self, name=None, attrs={}, recursive=True, text=None, **kwargs)

'''
find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.
比如文档中只有一个<body>标签,那么使用 find_all() 方法来查找<body>标签就不太合适, 
使用 find_all 方法并设置 limit=1 参数不如直接使用 find() 方法.下面两行代码是等价的:
'''
soup.find_all('title', limit=1)  # [<title>The Dormouse's story</title>]
soup.find('title')               # <title>The Dormouse's story</title>


# 唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果.
# find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None .
print(soup.find("nosuchtag"))  # None


# soup.head.title 是 tag的名字 方法的简写.这个简写的原理就是多次调用当前tag的 find() 方法:
soup.head.title  # <title>The Dormouse's story</title>
soup.find("head").find("title")  # <title>The Dormouse's story</title>

小结

soup.find('a') 等价 soup.a 等价 soup.find_all('a')[0]  等价 soup('a')[0]

soup.find('xxxx') 未找到返回None
soup.find_all('xxxx')[0]  和 soup('xxxx')[0]  未找到返回空列表[]

soup.head.a 就是 soup.find(head).find(a)的简写 

5.其他方法

https://www.cummy.com/software/BeautifulSoup/bs4/doc/indx.zh.html#find-parents-find-parent

6.CSS选择器

#css选择器是通用的

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p'>p的内容<b>The Dormouse's story<span>孙子</span></b><span>lqz</span></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" xx='xx'><span>lqz</span>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" name='lqz'>Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc, 'lxml')


# 括号中写css选择器
'''
直接写标签名
.类
#id
div>a  找div的子标签a
div a  找div的子子孙孙中的a

'''
# res=soup.select('.sister')
# res=soup.select('#link2')
# res=soup.select('p>b')
res=soup.select('p b')
print(res)


# bs4 可以修改xml格式的文档:后期可以会有一些配置文件是xml格式

小结

# 注意: select返回的结果是多个, 获取属性 或者 文本 都需要进行索引取值以后才能操作
soup.p.select('.sister')  
    soup.p(class_='sister') 
    soup.p.find_all(class_='sister')

soup.select('.sister span') 等价 
    li = []
    for sister in soup(class_='sister'):
        if not sister.span:
            continue
        span_list = sister('span')
        for span in span_list:
            li.append(span)
    print(li)
    
soup.select('#link1') 等价 soup(id='link1') 等价 soup.find_all(id='link1')

soup.select('#list-2 h1')[0].attrs 等价 
    soup.find(id='list-2').find_all('h1')[0].attrs 
    soup.find(id='list-2').find('h1').attrs   -> 优化

soup.select('#list-2 h1')[0].get_text() 等价
    soup.find(id='list-2').find('h1').text
    list(soup.find(id='list-2').find('h1').strings)

7. 修改文档树

bs4的修改文档树, 软件配置文件是xml格式的: https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id40

8. 通用性

拓展性: css选择器通用, find和find_all用的少. 有些解析器不支持

 

上一篇:python爬虫之Beautiful Soup库(3)


下一篇:Python爬虫常用库总结