03 爬虫解析库之bs4库

一. 介绍

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.你可能在寻找 Beautiful Soup3 的文档,Beautiful Soup 3 目前已经停止开发,官网推荐在现在的项目中使用Beautiful Soup 4, 移植到BS4

# 安装 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

下表列出了主要的解析器,以及它们的优缺点,官网推荐使用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. 用法

head = soup.head
print(head)  # <head><title>The Dormouse's story</title></head>

3. 获取标签的名称

head = soup.head
print(head.name, type(head.name))  # head <class 'str'>

4. 获取标签的属性

p = soup.body.p
print(p.attrs)  # {'class': ['title']}

# 注意: class可能有多个
# <a href="http://example.com/elsie" class="sister item" id="link1">Elsie</a>
a = soup.body.a
print(a.attrs)  # {'href': 'http://example.com/elsie', 'class': ['sister', 'item'], 'id': 'link1'}

5. 获取标签的内容

# <head><title>The Dormouse's story</title></head>
# <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>
# <a href="http://example.com/elsie" class="sister item" id="link1">Elsie</a>
head = soup.head
p = soup.body.p
a = soup.body.a

# .text: 获取标签下所有的文本内容
print(p.text)   # zhangchengDSB The Dormouse's story

# .string: 获取标签下只有一个文本内容存在的文本内容
print(p.string)     # None
print(a.string)     # Elsie
print(head.string)  # The Dormouse's story

# .strings: 获取标签下所有文本内容, 制作成一个迭代器对象
print(p.strings)        # <generator object _all_strings at 0x0000018C5FC5B4C0>
print(list(p.strings))  # ['zhangchengDSB ', "The Dormouse's story"]

6. 嵌套选择

# <a href="http://example.com/elsie" class="sister item" id="link1">Elsie</a>
a = soup.body.a
print(a)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>
print(a.get('id'))     # link1
print(a.get('class'))  # ['sister', 'item']

7. 子节点、子孙节点

# .contents: 获取标签下所有子节点 (注意: 包含空格等符号)
res = soup.body.p.contents
print(res)  # ['zhangchengDSB ', <b>The Dormouse's story</b>]

# .children: 获取标签下所有所有子节点, 制作成迭代器
res = soup.body.p.children
print(res)         # <list_iterator object at 0x00000205E078AE80>
print(list(res))   # ['zhangchengDSB ', <b>The Dormouse's story</b>]

8. 父节点、祖先节点

# .parent: 获取标签的父节点(单个)
res = soup.body.p.b.parent
print(res)  # <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>

# .parents: 获取标签的所有祖先节点
res = soup.a.parents
print(res)  # <generator object parents at 0x000001E206F4A4C0>
print(len(list(res)))  # 4 (提示: 这是一个迭代器, list取完了就空了)

res = soup.a.parents
print(list(res))
'''
[<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>, 

<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><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>, 

<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>]
'''

9. 兄弟节点

# .next_sibling: 获取标签的下一个兄弟 (提示: 逗号也被涵盖了, 不好用)
print(soup.a.next_sibling)
'''
<p class="title">zhangchengDSB <b>The Dormouse's story</b></p>
, 
'''

# .previous_sibling: 获取标签的上一个兄弟 (提示: 空格也被涵盖了, 也不好用)
print(soup.a.previous_sibling)
'''

Once upon a time there were three little sisters; and their names were
'''

10. 总结

# 注意: 多个标签结果之返回一条
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 获取标签的上一个兄弟 (提示: 空格也被涵盖了, 也不好用)

四. 搜索文档树

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

1) 字符串

'''
.find()        获取查询到的第一个 (提示: 内部本质还是调用了 find_all()[0])
.find_all()    获取查询到的所有
'''
# .find()
res = soup.find('a')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>
res = soup.find(name='a')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

res = soup.find(id='link1')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

res = soup.find(class_='sister')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

res = soup.find(attrs={'class': 'sister'})
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>
res = soup.find(attrs={'id': 'link1'})
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

# .find_all()
res = soup.find_all(class_='sister')
print(res)
'''
[
    <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>
]
'''

2) 正则表达式

import re

pattern = re.compile('^p')
res = soup.find(name=pattern)
print(res)  # <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>

res = soup.find_all(name=pattern)
print(res)
'''
[
    <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>
]
'''

3) 列表

res = soup.find_all(name=['b', 'a'])
print(res)
'''
[   <b>The Dormouse's story</b>, 
    <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>
]
'''

4) 布尔

res = soup.find_all(id=True)
print(res)
'''
[   
    <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>
]
'''

res = soup.find_all(href=True)
print(res)
'''
[   
    <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>
]
'''

5) 方法

# 如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False

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="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>
]
'''

6) 总结

# 字符串
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. 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)

3. 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)的简写 

4. 其它方法

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

5. CSS选择器

print(soup.p.select('.sister'))
'''
[
    <a class="sister" href="http://example.com/elsie" id="link1">
    <span>Elsie</span></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>
]
'''
res = soup.select('.sister span')
print(res)  # [<span>Elsie</span>]

res = soup.select('#link1')
print(res)  # [<a class="sister" href="http://example.com/elsie" id="link1"><span>Elsie</span></a>] 

res = soup.select('#link1 span')
print(res)  # [<span>Elsie</span>]

res = soup.select('#list-2 .element.xxx')
print(res)  # [<li class="element xxx">Bar</li>]

res = soup.select('#list-2')[0].select('.element')
print(res)  # 可以一直select,但其实没必要,一条select就可以了
'''
[<li class="element"><h1 class="yyyy">Foo</h1></li>, <li class="element xxx">Bar</li>, <li class="element">Jay</li>]
'''

# 2、获取属性
res = soup.select('#list-2 h1')[0].attrs
print(res)  # {'class': ['yyyy']}

# 3、获取内容
res = soup.select('#list-2 h1')[0].get_text()
print(res)  # Foo

总结

# 注意: 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)

6. 修改文档树

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

7. 通用性

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

posted @ 2020-08-04 07:40  给你加马桶唱疏通  阅读(213)  评论(0编辑  收藏  举报