爬虫解析bs4

一. 介绍#

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

Copy
# 安装 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解析方法不够稳定.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.htmlhtml5

二. 基本使用#

Copy
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. 介绍#

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

# 一、用法
# 二、获取标签的名称
# 三、获取标签的属性
# 四、获取标签的内容
# 五、嵌套选择
# 六、子节点、子孙节点
# 七、父节点、祖先节点
# 八、兄弟节点

2. 用法#

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

3. 获取标签的名称#

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

4. 获取标签的属性#

Copy
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. 获取标签的内容#

Copy
# <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. 嵌套选择#

Copy
# <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. 子节点、子孙节点#

Copy
# .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. 父节点、祖先节点#

Copy
# .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. 兄弟节点#

Copy
# .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. 总结#

Copy
# 注意: 多个标签结果之返回一条
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) 字符串#

Copy
''' .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) 正则表达式#

Copy
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) 列表#

Copy
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) 布尔#

Copy
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) 方法#

Copy
# 若是没有合适过滤器,那么还能够定义一个方法,方法只接受一个元素参数 ,若是这个方法返回 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) 总结#

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

Copy
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))  # []

总结正则表达式

Copy
# 参数: 
    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)express

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

总结浏览器

Copy
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-parentmarkdown

5. CSS选择器#

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

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

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

总结app

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

7. 通用性#

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

相关文章
相关标签/搜索