Python爬虫初级(三)—— Beautiful Soup 库入门

欢迎关注公众号K的笔记阅读博主更多优质学习内容
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爬虫初级(四)—— 信息组织与提取方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值