欢迎关注公众号K的笔记阅读博主更多优质学习内容
上一篇内容:Python爬虫初级(二)—— Requests 网络爬虫实战
BeautifulSoup 库的安装
安装beautiful soup 库可以直接使用命令 pip install beautifulsoup4,安装完成之后可以通过演示 HTML 页面地址:http://python123.io/ws/demo.html 进行测试。我们打开这个网址,查询源代码,得到下面的结果:
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>
</body></html>
我们刚刚查看源代码是直接右键查看源代码进行拷贝的,除此之外,我们还可以使用 requests 库自动获得该链接的源代码:
import requests
from bs4 import BeautifulSoup
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, "html.parser")
print(soup.prettify())
这是上述代码的返回结果:
<html>
<head>
<title>
This is a python demo page
</title>
</head>
<body>
<p class="title">
<b>
The demo python introduces several python courses.
</b>
</p>
<p class="course">
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
Basic Python
</a>
and
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
Advanced Python
</a>
</p>
</body>
</html>
看得出来,这个效果还是蛮好看的。实际上,Beautiful Soup 库是解析、遍历和维护“标签树”的功能库,可以理解为:BeautifulSoup 对应一个 HTML/XML 文档的全部内容。
BeautifulSoup 库详解
BeautifulSoup 库的解析器一共有四种,分别列举如下:
解析器 | 使用方法 | 条件 |
---|---|---|
bs4 的 HTML 解析器 | BeautifulSoup(mk, “html.parser”) | pip install bs4 |
lxml 的 HTML 解析器 | BeautifulSoup(mk, “lxml”) | pip install lxml |
lxml 的 XML 解析器 | BeautifulSoup(mk, “xml”) | pip install lxml |
html5lib 的解析器 | BeautifulSoup(mk, “html5lib”) | pip install html5lib |
BeautifulSoup 类的基本元素列举如下:
基本元素 | 说明 |
---|---|
Tag | 标签,最基本的信息组织单元,分别用 <> 和 </>标明开头和结尾 |
Name | 标签的名字,获取格式:<tag>.name |
Attributes | 标签的属性,获取格式:<tag>.attrs |
NavigableString | 标签内非属性字符串,获取格式:<tag>.string |
Comment | 标签内字符串的注释部分,一种特殊的Comment类型 |
我们可以对前面获得的 soup 进行 尝试:
print(soup.title)
# 返回 <title>This is a python demo page</title>
tag = soup.a
print(tag)
# 返回 <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
print(soup.a.parent.name) # 返回 'p'
print(soup.a.parent.parent.name) # 返回 'body'
print(tag.attrs)
# 返回 {'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
prin(soup.a.string) # 返回 Basic Python
我们需要注意的是,当我们的 HTML 存在多个相同的标签时,只会返回第一个。我们再来看一下 Comment 元素的使用:
newsoup = Beautiful("<b><!--This is a comment--></b><p>This is not a comment</p>", "html.parser")
print(newsoup.b.string) # 返回 'This is a comment'
print(newsoup.p.string) # 返回 'This is not a comment'
我们总结一下,对于 < p class=“title”> … </p>,若要得到 p ,我们使用: .name,若要得到 class=“title”,我们使用:属性.attrs,若要得到 title,我们使用**标签.<tag> **,若要得到…(文本),我们使用:非属性字符串/注释.string
基于 bs4 库的 HTML 内容遍历方法
在 HTML 中我们有三种遍历方式 —— 上行遍历、下行遍历和平行遍历,下面分别介绍这几种遍历的直接方法。
标签树的下行遍历
属性 | 说明 |
---|---|
.contents | 子节点的列表,将 <tag> 所有儿子节点存入列表 |
.children | 子节点的迭代类型,与 .contents 类似,用于循环遍历儿子节点 |
.descendants | 子孙节点的迭代类型,包括所有子孙节点,用于循环遍历 |
例如:
>>> soup = BeautifulSoup(demo, "html.parser")
>
>>> soup.head
<head><title>This is a python demo page</title></head>
>>>soup.head.contents
[<title>This is a python demo page</title>]
>>> soup.body.contents
['\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, '\n', <p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>, '\n']
>>> len(soup.body.contents)
5
>>> soup.body.contents[1]
<p class="title"><b>The demo python introduces several python courses.</b></p>
标签树的上行遍历
属性 | 说明 |
---|---|
.parent | 节点的父亲标签 |
.parents | 节点父辈标签的迭代类型,用于循环遍历先辈节点 |
下面是上行遍历的代码:
>>> soup = BeautifulSoup(demo, "html.parser")
>>> for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
p
body
html
[document]
标签树的平行遍历
属性 | 说明 |
---|---|
.next_sibling | 返回按照 HTML 文本顺序的下一个平行节点标签 |
.previous_sibling | 返回按照 HTML 文本顺序的上一个平行节点标签 |
.next_siblings | 返回按照 HTML 文本顺序的后续所有平行节点标签 |
.previous_siblings | 返回按照 HTML 文本顺序的前续所有平行节点标签 |
需要注意的是:平行遍历发生在同一个父节点下的各节点间。
还记得我们前面的那个标签树吗?我们截取一部分来回顾一下:
<p class="course">
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
Basic Python
</a>
and
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
我们接下来对 a 标签进行简单的平行遍历尝试:
>>> soup = BeautifulSoup(demo, "html.parser")
>>> soup.a.next_sibling
' and '
>>> soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
>>> soup.a.previous_sibling
'Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n'
我们可以通过以下代码做标签树的平行遍历:
for sibling in soup.a.next_siblings:
print(sibling)
for sibling in soup.a.previous_siblings:
print(sibling)
基于 bs4 库的 HTML 格式输出
我们应该如何让 <html> 内容更加友好地输出呢?就是我们前面使用的 BeautifulSoup.prettify() 函数来实现。
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("<p> 中文 china </p>","html.parser")
>>> soup.prettify()
'<p>\n 中文 china\n</p>'
>>> print(soup.prettify())
<p>
中文 china
</p>
下面附上一张总结(截)图:
下一篇内容:Python爬虫初级(四)—— 信息组织与提取方法