之前的文章我们介绍了 re 模块和 lxml 模块来做爬虫,本章我们再来看一个 bs4 模块来做爬虫。

和 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 安装即可:pip install beautifulsoup4

官方文档:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0

抓取工具 速度 使用难度 安装难度
正则 最快 困难 无(内置)
BeautifulSoup 最简单 简单
lxml 简单 一般

首先必须要导入 bs4 库

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17.  
  18. # 打开本地 HTML 文件的方式来创建对象
  19. # soup = BeautifulSoup(open('index.html'), "lxml")
  20.  
  21. # 格式化输出 soup 对象的内容
  22. print(soup.prettify())

运行结果:

  1. <html>
  2. <body>
  3. <div>
  4. <ul>
  5. <li class="item-0">
  6. <a href="link1.html">
  7. first item
  8. </a>
  9. </li>
  10. <li class="item-1">
  11. <a href="link2.html">
  12. second item
  13. </a>
  14. </li>
  15. <li class="item-inactive">
  16. <a href="link3.html">
  17. <span class="bold">
  18. third item
  19. </span>
  20. </a>
  21. </li>
  22. <li class="item-1">
  23. <a href="link4.html">
  24. fourth item
  25. </a>
  26. </li>
  27. <li class="item-0">
  28. <a href="link5.html">
  29. fifth item
  30. </a>
  31. </li>
  32. </ul>
  33. </div>
  34. </body>
  35. </html>

四大对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

1. Tag

Tag 通俗点讲就是 HTML 中的一个个标签,例如:

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17.  
  18. print(soup.li) # <li class="item-0"><a href="link1.html">first item</a></li>
  19. print(soup.a) # <a href="link1.html">first item</a>
  20. print(soup.span) # <span class="bold">third item</span>
  21. print(soup.p) # None
  22. print(type(soup.li)) # <class 'bs4.element.Tag'>

我们可以利用 soup 加标签名轻松地获取这些标签的内容,这些对象的类型是bs4.element.Tag。但是注意,它查找的是在所有内容中的第一个符合要求的标签。如果要查询所有的标签,后面会进行介绍。

对于 Tag,它有两个重要的属性,是 name 和 attrs
  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17.  
  18. print(soup.li.attrs) # {'class': ['item-0']}
  19. print(soup.li["class"]) # ['item-0']
  20. print(soup.li.get('class')) # ['item-0']
  21.  
  22. print(soup.li) # <li class="item-0"><a href="link1.html">first item</a></li>
  23. soup.li["class"] = "newClass" # 可以对这些属性和内容等等进行修改
  24. print(soup.li) # <li class="newClass"><a href="link1.html">first item</a></li>
  25.  
  26. del soup.li['class'] # 还可以对这个属性进行删除
  27. print(soup.li) # <li><a href="link1.html">first item</a></li>

2. NavigableString

既然我们已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用 .string 即可,例如

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17.  
  18. print(soup.li.string) # first item
  19. print(soup.a.string) # first item
  20. print(soup.span.string) # third item
  21. # print(soup.p.string) # AttributeError: 'NoneType' object has no attribute 'string'
  22. print(type(soup.li.string)) # <class 'bs4.element.NavigableString'>

3. BeautifulSoup

BeautifulSoup 对象表示的是一个文档的内容。大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17.  
  18. print(soup.name) # [document]
  19. print(soup.attrs) # {}, 文档本身的属性为空
  20. print(type(soup.name)) # <class 'str'>

4. Comment

Comment 对象是一个特殊类型的 NavigableString 对象,其输出的内容不包括注释符号。

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
  6. </div>
  7. """
  8.  
  9. # 创建 Beautiful Soup 对象
  10. soup = BeautifulSoup(html, "lxml")
  11.  
  12. print(soup.a) # <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
  13. print(soup.a.string) # Elsie
  14. print(type(soup.a.string)) # <class 'bs4.element.Comment'>

a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容时,注释符号已经去掉了。

遍历文档树

1. 直接子节点 :.contents .children 属性

.content

tag 的 .content 属性可以将tag的子节点以列表的方式输出,输出方式为列表,我们可以用列表索引来获取它的某一个元素

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17.  
  18. print(soup.li.contents) # [<a href="link1.html">first item</a>]
  19. print(soup.li.contents[0]) # <a href="link1.html">first item</a>

.children

它返回的不是一个 list,不过我们可以通过遍历获取所有子节点。

我们打印输出 .children 看一下,可以发现它是一个 list 生成器对象

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17.  
  18. print(soup.ul.children) # <list_iterator object at 0x106388a20>
  19. for child in soup.ul.children:
  20. print(child)

输出结果:

  1. <li class="item-0"><a href="link1.html">first item</a></li>
  2.  
  3. <li class="item-1"><a href="link2.html">second item</a></li>
  4.  
  5. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  6.  
  7. <li class="item-1"><a href="link4.html">fourth item</a></li>
  8.  
  9. <li class="item-0"><a href="link5.html">fifth item</a></li>

2. 所有子孙节点: .descendants 属性

.contents 和 .children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环,和 children类似,我们也需要遍历获取其中的内容。

  1. for child in soup.ul.descendants:
  2. print(child)

运行结果:

  1. <li class="item-0"><a href="link1.html">first item</a></li>
  2. <a href="link1.html">first item</a>
  3. first item
  4.  
  5. <li class="item-1"><a href="link2.html">second item</a></li>
  6. <a href="link2.html">second item</a>
  7. second item
  8.  
  9. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  10. <a href="link3.html"><span class="bold">third item</span></a>
  11. <span class="bold">third item</span>
  12. third item
  13.  
  14. <li class="item-1"><a href="link4.html">fourth item</a></li>
  15. <a href="link4.html">fourth item</a>
  16. fourth item
  17.  
  18. <li class="item-0"><a href="link5.html">fifth item</a></li>
  19. <a href="link5.html">fifth item</a>
  20. fifth item

搜索文档树

1.find_all(name, attrs, recursive, text, **kwargs)

1)name 参数

name 参数可以查找所有名字为 name 的 tag,字符串对象会被自动忽略掉

A.传字符串

最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<span>标签:

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17. print(soup.find_all('span')) # [<span class="bold">third item</span>]
B.传正则表达式

如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以 s 开头的标签,这表示 <span标签都应该被找到

  1. from bs4 import BeautifulSoup
  2. import re
  3.  
  4. html = """
  5. <div>
  6. <ul>
  7. <li class="item-0"><a href="link1.html">first item</a></li>
  8. <li class="item-1"><a href="link2.html">second item</a></li>
  9. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  10. <li class="item-1"><a href="link4.html">fourth item</a></li>
  11. <li class="item-0"><a href="link5.html">fifth item</a></li>
  12. </ul>
  13. </div>
  14. """
  15.  
  16. # 创建 Beautiful Soup 对象
  17. soup = BeautifulSoup(html, "lxml")
  18. for tag in soup.find_all(re.compile("^s")):
  19. print(tag)
  20. # <span class="bold">third item</span>
C.传列表

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有 <a> 标签和 <span> 标签:

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17. print(soup.find_all(["a", "span"]))
  18. # [<a href="link1.html">first item</a>, <a href="link2.html">second item</a>, <a href="link3.html"><span class="bold">third item</span></a>, <span class="bold">third item</span>, <a href="link4.html">fourth item</a>, <a href="link5.html">fifth item</a>]

2)keyword 参数

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <div>
  5. <ul>
  6. <li class="item-0"><a href="link1.html">first item</a></li>
  7. <li class="item-1"><a href="link2.html">second item</a></li>
  8. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  9. <li class="item-1"><a href="link4.html">fourth item</a></li>
  10. <li class="item-0"><a href="link5.html">fifth item</a></li>
  11. </ul>
  12. </div>
  13. """
  14.  
  15. # 创建 Beautiful Soup 对象
  16. soup = BeautifulSoup(html, "lxml")
  17. print(soup.find_all(href='link1.html')) # [<a href="link1.html">first item</a>]

3)text 参数

通过 text 参数可以搜搜文档中的字符串内容,与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表

  1. from bs4 import BeautifulSoup
  2. import re
  3.  
  4. html = """
  5. <div>
  6. <ul>
  7. <li class="item-0"><a href="link1.html">first item</a></li>
  8. <li class="item-1"><a href="link2.html">second item</a></li>
  9. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  10. <li class="item-1"><a href="link4.html">fourth item</a></li>
  11. <li class="item-0"><a href="link5.html">fifth item</a></li>
  12. </ul>
  13. </div>
  14. """
  15.  
  16. # 创建 Beautiful Soup 对象
  17. soup = BeautifulSoup(html, "lxml")
  18. print(soup.find_all(text="first item")) # ['first item']
  19. print(soup.find_all(text=["first item", "second item"])) # ['first item', 'second item']
  20. print(soup.find_all(text=re.compile("item"))) # ['first item', 'second item', 'third item', 'fourth item', 'fifth item']

CSS选择器

这就是另一种与 find_all 方法有异曲同工之妙的查找方法.

  • 写 CSS 时,标签名不加任何修饰,类名前加.,id名前加#

  • 在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list

(1)通过标签名查找

  1. from bs4 import BeautifulSoup
  2. import re
  3.  
  4. html = """
  5. <div>
  6. <ul>
  7. <li class="item-0"><a href="link1.html">first item</a></li>
  8. <li class="item-1"><a href="link2.html">second item</a></li>
  9. <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
  10. <li class="item-1"><a href="link4.html">fourth item</a></li>
  11. <li class="item-0"><a href="link5.html">fifth item</a></li>
  12. </ul>
  13. </div>
  14. """
  15.  
  16. # 创建 Beautiful Soup 对象
  17. soup = BeautifulSoup(html, "lxml")
  18. print(soup.select('span')) # [<span class="bold">third item</span>]

(2)通过类名查找

  1. print(soup.select('.item-0'))
  2. # [<li class="item-0"><a href="link1.html">first item</a></li>, <li class="item-0"><a href="link5.html">fifth item</a></li>]

(3)通过 id 名查找

  1. print(soup.select('#item-0')) # []

(4)组合查找

  1. print(soup.select('li.item-0'))
  2. # [<li class="item-0"><a href="link1.html">first item</a></li>, <li class="item-0"><a href="link5.html">fifth item</a></li>]
  3. print(soup.select('li.item-0>a'))
  4. # [<a href="link1.html">first item</a>, <a href="link5.html">fifth item</a>]

(5)属性查找

  1. print(soup.select('a[href="link1.html"]')) # [<a href="link1.html">first item</a>]

(6) 获取内容

  1. for text in soup.select('li'):
  2. print(text.get_text())
  3. """
  4. first item
  5. second item
  6. third item
  7. fourth item
  8. fifth item
  9. """

Python 爬虫从入门到进阶之路(十二)的更多相关文章

  1. Python 爬虫从入门到进阶之路(二)

    上一篇文章我们对爬虫有了一个初步认识,本篇文章我们开始学习 Python 爬虫实例. 在 Python 中有很多库可以用来抓取网页,其中内置了 urllib 模块,该模块就能实现我们基本的网页爬取. ...

  2. Python 爬虫从入门到进阶之路(八)

    在之前的文章中我们介绍了一下 requests 模块,今天我们再来看一下 Python 爬虫中的正则表达的使用和 re 模块. 实际上爬虫一共就四个主要步骤: 明确目标 (要知道你准备在哪个范围或者网 ...

  3. Python 爬虫从入门到进阶之路(六)

    在之前的文章中我们介绍了一下 opener 应用中的 ProxyHandler 处理器(代理设置),本篇文章我们再来看一下 opener 中的 Cookie 的使用. Cookie 是指某些网站服务器 ...

  4. Python 爬虫从入门到进阶之路(九)

    之前的文章我们介绍了一下 Python 中的正则表达式和与爬虫正则相关的 re 模块,本章我们就利用正则表达式和 re 模块来做一个案例,爬取<糗事百科>的糗事并存储到本地. 我们要爬取的 ...

  5. Python 爬虫从入门到进阶之路(十五)

    之前的文章我们介绍了一下 Python 的 json 模块,本章我们就介绍一下之前根据 Xpath 模块做的爬取<糗事百科>的糗事进行丰富和完善. 在 Xpath 模块的爬取糗百的案例中我 ...

  6. Python 爬虫从入门到进阶之路(十六)

    之前的文章我们介绍了几种可以爬取网站信息的模块,并根据这些模块爬取了<糗事百科>的糗百内容,本章我们来看一下用于专门爬取网站信息的框架 Scrapy. Scrapy是用纯Python实现一 ...

  7. Python 爬虫从入门到进阶之路(十七)

    在之前的文章中我们介绍了 scrapy 框架并给予 scrapy 框架写了一个爬虫来爬取<糗事百科>的糗事,本章我们继续说一下 scrapy 框架并对之前的糗百爬虫做一下优化和丰富. 在上 ...

  8. Python 爬虫从入门到进阶之路(五)

    在之前的文章中我们带入了 opener 方法,接下来我们看一下 opener 应用中的 ProxyHandler 处理器(代理设置). 使用代理IP,这是爬虫/反爬虫的第二大招,通常也是最好用的. 很 ...

  9. Python 爬虫从入门到进阶之路(七)

    在之前的文章中我们一直用到的库是 urllib.request,该库已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 “HTTP for Hum ...

随机推荐

  1. ODBC、OLEDB和ADO关系

    知道.net影片后,相关数据库的一些概念连接的内侧部分是很无语.互联网是非常多的相关信息,外,基本上内容都神一样的一致. 如今.我就通过结合看到的一些资料再加上自己的理解试图去解释一下,有不正确的.还 ...

  2. 【剑指offer】直扑克

    个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想測測自己的手气,看看能不能抽到顺子,假设抽到的话,他决定去买体育彩票,嘿嘿! ! "红心A,黑桃3,小王,大王,方 ...

  3. 使用WPF技术模拟手机界面

    原文:使用WPF技术模拟手机界面 1. 前言 WPF(Windows Presentation Foundation),即"Windows呈现基础",它的目的非常明确,就是用来把数 ...

  4. String转Color

    原文:String转Color 很硬性的转换,谁知道更好的忘不吝赐教啊. /// <summary> /// String To Color /// </summary> // ...

  5. 如何自定义WPF项目的Main函数

    原文:如何自定义WPF项目的Main函数 与Winform项目不同,WPF项目的Main函数在项目生成的时候,系统自动在后台为我们生成.根据项目生成方式的不同,其文件位于obj/Debug/App.g ...

  6. SignalR QuickStart

    原文:SignalR QuickStart SignalR 是一个集成的客户端与服务器库,基于浏览器的客户端和基于 ASP.NET 的服务器组件可以借助它来进行双向多步对话. 换句话说,该对话可不受限 ...

  7. ADB 基础命令使用

    1.adb shell(>=2个设备显示:error: more than one device/emulator,仅连接一个设备可用) adb -d shell 只运行在真实设备中 adb - ...

  8. 微信小程序把玩(六)模块化

    原文:微信小程序把玩(六)模块化 模块化也就是将一些通用的东西抽出来放到一个文件中,通过module.exports去暴露接口.我们在最初新建项目时就有个util.js文件就是被模块化处理时间的 /* ...

  9. [转] Protobuf高效结构化数据存储格式

    从公司的项目源码中看到了这个东西,觉得挺好用的,写篇博客做下小总结.下面的操作以C++为编程语言,protoc的版本为libprotoc 3.2.0. 一.Protobuf? 1. 是什么?  Goo ...

  10. Ruby已经慢慢走向衰退了,那些年代久远而且小众的语言没有翻身的可能性

    Ruby已经慢慢走向衰退了,现在WEB开发里,NODE.JS+前端各种框架是主流,PHP.ruby.Asp.net.python等语言在网站编程方面只会越来越少.数据领域方面,机器学习和人工智能中,p ...