python_爬虫收藏Python 原生爬虫教程

10《Python 原生爬虫教程》BeatifulSoup 的使

2022-03-01  本文已影响0人  木子教程

还记得之前我们在第一个爬虫案例中使用过的 BeatifulSoup 吗?这节课我们就来正式学习一下 BeatifulSoup 这个页面提取工具,通过本节课的学习你会熟悉使用 BeatifulSoup 提取常见的网页元素。

1. BeatifulSoup 简介

使用 Requests 获取到页面源码后,我们需要一种工具来帮助我们结构化这些数据,从而方便我们检索需要的某个或者某些数据内容。BeautifulSoup 库就是这样一种工具,可以很方便我们对数据进行解析和数据的提取。

BeautifulSoup 的名字来源于大家耳熟能详的一部外国名著里面的小说,这部小说的名字叫做《爱丽丝梦游仙境》。从名字就可以看出,发明这个库的作者的目的是为了让使用这个库的人,心情舒畅,使用起来很方便舒适,接口简单人性化。

2. 安装 BeautifulSoup

因为 BeautifulSoup 并不是 Python 内置的库,我们需要额外安装它。我们现在普遍使用的版本是 BeautifulSoup4, 简称作 bs4。

使用 pip 来安装 BeautifulSoup 很简单,打开 CMD 窗口运行下面这条命令:

pip install beautifulsoup4

安装成功后,如图所示:

5e7cc3b70939ff1c05700452.jpg

2. BeatifuSoup 解析器

解析器是一种帮我们结构化网页内容的工具,通过解析器,我们可以得到结构化的数据,而不是单纯的字符,方便我们解析和查找数据。

BeautifulSoup 的解析器有 html.parse,html5lib,lxml 等。BeautifulSoup 本身支持的标准库是 html.parse,html5lib。但是,lxml 的性能非常棒,以及拥有良好的容错能力,现在被广泛的使用。

解析器对比:

安装 lxml 和安装 BeautifulSoup 类似,同样只需一行命令就好:

pip install lxml

安装成功后,如下所示:

5e7cc3cd098ce81705700452.png

3. BeautifulSoup 的四类对象

BeautifulSoup 将 HTML 转换成树形结构,每个节点都是 Python 对象,所有对象可以归纳为 4 种:

下面我们一一来看下这四类对象:

<title></title>

<title>木子微课</title>

<!-- 木子微课 -->

4. BeautifulSoup 搜索文档树

下面我们就来具体使用一下 BeautifulSoup 这个解析工具,我们首先模仿 HTML 页面结构创建一个字符串:

<html>
<head>
<title>hello world</title>
</head>
<body>
<div>
<p class="p-one a-item" id="aaa">python introduction</p>
<p class="p-one">Basic Python Class</p>
</div>
<p class="p-two a-item" id="bbb"><b>Java introduction</b></p>
<p class="p-two"><b>Basic Java Class</b></p>
</body>
</html>

4.1 字符串

from bs4 import BeautifulSoup
soup = BeautifulSoup (open("bs4.html"), features="lxml")
soup.find_all('p')

5e7cc3dd096a245415120441.jpg

4.2 正则表达式

from bs4 import BeautifulSoup
import re
soup = BeautifulSoup (open("bs4.html"), features="lxml")
for tag in soup.find_all(re.compile("b")):
    print(tag.name)

5e7cc3e609bec6d915010229.jpg

4.3 列表

from bs4 import BeautifulSoup
soup = BeautifulSoup (open("bs4.html"), features="lxml")
soup.find_all(["a", "b"])

5e7cc3f009e4033615150470.png

4.4 搜索属性

from bs4 import BeautifulSoup
soup = BeautifulSoup (open("bs4.html"), features="lxml")
soup.find_all("p", id="aaa")

5e7cc3f909b1cd1215260178.jpg

4.5 搜索字符串内容

from bs4 import BeautifulSoup
soup = BeautifulSoup (open("bs4.html"), features="lxml")
soup.find_all(string="Java")

5e7cc40409cd2fbb15190091.jpg

4.6 搜索 CSS

5e7cc435094c1b5015170146.jpg
from bs4 import BeautifulSoup
soup = BeautifulSoup (open("bs4.html"), features="lxml")
soup.find_all(["a", "b"])

5e7cc40409cd2fbb15190091.jpg

5. 小结

工作中,我们一般经常的使用的方法就是 find_all 方法。但是,除了上述我们讲的 find_all 方法之外,BeautifulSoup 还有其他一些以 find 开头的方法,由于不是经常使用,这里就简单的列举一下,如果同学们感兴趣的话可以自己深入了解下。

方法名称 作用
find_all() 搜索当前节点的所有子节点和孙子节点,并直接返回所有结果。
find_parents/find_parent 搜索当前节点的父亲节点
find_next_siblings/find_next_sibling 搜索所有的后续的兄弟节点
find_previous_siblings/find_previous_sibling 搜有当前的兄弟节点
find_all_next()/find_next 对当前节点的后续标签和字符串进行循环迭代
find_all_previous/find_previous 对当前节点的前面标签和字符串进行循环迭代
上一篇下一篇

猜你喜欢

热点阅读