python爬虫基础html内容解析库BeautifulSoup

news/2024/7/19 11:27:16 标签: python, 爬虫, html

我们通过Requests请求url获取数据,请求把数据返回来之后就要提取目标数据,不同的网站返回的内容通常有多种不同的格式,一种是 json 格式,我们可以直接通过json.loads转换html" title=python>python的json对象处理。另一种 XML 格式的,还有一种最常见格式的是 HTML 文档,今天就来讲讲如何从 HTML 中提取出感兴趣的数据。

BeautifulSoup 是一个用于解析 HTML 文档的 Python 库,通过 BeautifulSoup,你只需要用很少的代码就可以提取出 HTML 中任何感兴趣的内容,此外,它还有一定的 HTML 容错能力,对于一个格式不完整的HTML 文档,它也可以正确处理。

安装 beautifulsoup

pip install beautifulsoup4

初始化对象时可以直接传递字符串或者文件句柄

html" title=python>python">soup = BeautifulSoup(open("index.html"))
soup = BeautifulSoup("<html>data</html>")

支持多种解析接口

html" title=python>python"># html" title=python>python内置HTML解析
BeautifulSoup(markup, "html.parser")
# lxml语言支持HTML解析
BeautifulSoup(markup, "lxml")
# 解析XML引擎
BeautifulSoup(markup, "xml")
# 解析HTML5引擎
BeautifulSoup(markup, "html5lib")

自动添加和补全标签

下面是一段不规范的html,缺少闭合标签

html" title=python>python">html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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" 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>
"""
  • 它由很多标签(Tag)组成,比如 html、head、title等等都是标签
  • 一个标签对构成一个节点,比如 …是一个根节点
  • 节点之间存在某种关系,比如p之间互为邻居,他们是相邻的兄弟(sibling)节点
  • p 是 body 的直接子(children)节点,还是 html 的子孙(descendants)节点
  • body 是 p 的父(parent)节点,html 是 p 的祖辈(parents)节点
  • 嵌套在标签之间的字符串是该节点下的一个特殊子节点,比如title文本内容“The Dormouse’sstory”也是一个节点,只不过没名字。
html" title=python>python">
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())

prettify()标准缩进格式的输出。输出内容如下:

html"> <html>
  <head>
   <title>
   The Dormouse's story
   </title>
  </head>
  <body>
   <p class="title">
    <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" 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="link2">
     Tillie
    </a>
    ; and they lived at the bottom of a well.
  </p>
   <p class="story">
    ...
   </p>
  </body>
 </html>

bs4获取标签及内容示例

html" title=python>python">
# title标签
soup.title
# <title>The Dormouse's story</title>

# title标签名称
soup.title.name
# 'title'

# # title标签的文本字符内容
soup.title.string
# 'The Dormouse's story'

# title标签父节点名称
soup.title.parent.name
# 'head'

# 从前向后找到html孙节点第一个p节点
soup.p
# <p class="title"><b>The Dormouse's story</b></p>

# p节点的class属性
soup.p['class']
# ['title']

# 进栈出栈的方式找到第一个a标签
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

# p节点的href属性
soup.a["href"]
# 'http://example.com/elsie'

soup.find_all('a')
# 同上
soup.find_all("p")[1].find_all("a")

# [<a class="sister" 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>]

soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

遍历文档树

从根节点 html 标签开始遍历,元素进栈出栈,直到找到目标元素为止。

BeatifulSoup 将 HTML 抽象成为 4 类主要的数据类型:

  • Tag:每个标签节点就是一个Tag对象
  • NavigableString:包裹在Tag对象里的文本字符串
  • BeautifulSoup 对象代表要解析的整个
  • Comment注释对象
html" title=python>python">
type(soup)
# <class 'bs4.BeautifulSoup'>
type(soup.p)
# <class 'bs4.element.Tag'>
# type(soup.p.string)
<class 'bs4.element.NavigableString'>

Tag标签

每个 Tag 都有一个名字,它对应 HTML 的标签名称。

html" title=python>python">soup.p.name
# 'p'

标签有属性,属性的访问方式和字典是类似的,它返回一个列表对象或字符串。

html" title=python>python">soup.p['class']
# ['title']

soup.a['href']
# 'http://example.com/elsie'

NavigableString
获取标签中的内容,直接使用 .stirng 即可获取,它是一个 NavigableString 对象 。

html" title=python>python">soup.p.string
# "The Dormouse's story"
type(soup.p.string)
bs4.element.NavigableString

搜索文档树

搜索文档树是通过指定标签名来搜索元素,还可以通过指定标签的属性值来精确定位某个节点元素,最常用的两个方法就是 find 和 find_all。这两个方法在 BeatifulSoup 和 Tag 对象上都可以被调用。

find_all()方法

html" title=python>python">find_all( name , attrs , recursive , text , **kwargs )

第一个参数 name 是标签节点的名字。

html" title=python>python"># 所有p标签
soup.find_all("p")

# [<p class="title"><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" 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>]

第二个参数是标签的class属性值

html" title=python>python">soup.find_all("p","title")
# 同上
soup.find_all("p",class_ ="title")

# [<p class="title"><b>The Dormouse's story</b></p>]

kwargs 是标签的属性名值对。

html" title=python>python">import re
# 支持使用标签属性
soup.find_all(href="http://example.com/lacie")
soup.find_all(id="link2")

# 支持使用正则
soup.find_all(href=re.compile("lacie"))
 
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

# 支持使用布尔类型
soup.find_all('a',id=True)

遍历和搜索相结合,先定位到 body 标签,再从 body 中找 a 标签.。

html" title=python>python">soup.body.find_all('a',id=True)

find()方法

find 方法跟 find_all 类似,唯一不同的地方是,它返回的单个 Tag 对象而非列表,如果没找到匹配的节点则返回 None。如果匹配多个 Tag,只返回第0个。

html" title=python>python">soup.body.find("a")
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

get_text()方法
获取标签里面内容,除了可以使用 .string 之外,还可以使用 get_text 方法,不同的地方在于前者返回的一个 NavigableString 对象,后者返回的是 字符串。

html" title=python>python">soup.body.find("a").get_text()
# Elsie

实际场景中我们一般使用 get_text 方法获取标签中的内容。

总结:

通过beautifulsoup我们能够解析大部分静态html网页,遍历和搜索组合方式定位html的标签,并获取相应标签的内容。

在这里插入图片描述


http://www.niftyadmin.cn/n/5238335.html

相关文章

【Flink】Flink核心概念简述

目录 一、Flink 简介二、Flink 组件栈1. API & Libraries 层2. runtime层3. 物理部署层 三、Flink 集群架构四、Flink基本编程模型五、Flink 的优点 一、Flink 简介 Apache Flink 的前身是柏林理工大学一个研究性项目&#xff0c; 在 2014 被 Apache 孵化器所接受&#xf…

ubuntu 创建conda 环境失败 HTTP 000 CONNECTION FAILED

如有帮助点赞收藏关注&#xff01; 如需转载&#xff0c;请注明出处&#xff01; 现在内存分配好了&#xff0c;创建一个专门的conda环境处理文件&#xff0c;报错了&#xff0c;创建不成功&#xff01; 什么情况&#xff0c;之前明明可以的。 百度吧。 参照一些博客修改了文档…

举例说明自然语言处理(NLP)技术。

本文章由AI生成&#xff01; 以下是自然语言处理&#xff08;NLP&#xff09;技术的一些例子&#xff1a; 机器翻译&#xff1a;将一种语言翻译成另一种语言的自动化过程。常见的机器翻译系统包括谷歌翻译&#xff0c;百度翻译等。 语音识别&#xff1a;将口头语言转换成文本…

蓝桥杯网络安全组竞赛

竞赛规则及说明 选拔赛时长&#xff1a;4h 决赛时长&#xff1a;4h 竞赛形式&#xff1a;线上比赛&#xff1a; 个人赛&#xff1a;一人一机&#xff0c;全程机考 大赛制定竞赛系统&#xff0c;在时间内提交答案到比赛系统&#xff0c;超时无法提交 机器环境&#xff1a; 电脑…

14、策略模式(Strategy Pattern)

策略模式&#xff08;Strategy Pattern&#xff09;为同一个行为定义了不同的策略&#xff0c;并为每种策略都实现了不同的方法。在用户使用的时候&#xff0c;系统根据不同的策略自动切换不同的方法来实现策略的改变。同一个策略下的不同方法是对同一功能的不同实现&#xff0…

ChatGPT持续爆火,教育系统要应对哪些挑战?

ChatGPT爆火两个月&#xff0c;整个教育系统都在被颠覆。在全美范围内&#xff0c;许多大学教授、系主任和管理人员&#xff0c;都在对课堂进行大规模的调整&#xff0c;以应对ChatGPT对教学活动造成的巨大冲击。 我们的传统中高考选出的分霸&#xff0c;是更能吃苦&#xff0…

使用激光雷达(LiDAR)和相机进行3D物体跟踪

使用相机和激光雷达进行时间到碰撞&#xff08;TTC&#xff09;计算 在我的先前文章中&#xff0c;我介绍了通过检测关键点和匹配描述符进行2D特征跟踪的主题。在本文中&#xff0c;我将利用这些文章中的概念&#xff0c;以及更多的内容&#xff0c;开发一个软件流水线&#xf…

牛客算法题 【HJ91 走方格的方案数】 golang实现

题目 HJ91 走方格的方案数 描述 请计算n*m的棋盘格子&#xff08;n为横向的格子数&#xff0c;m为竖向的格子数&#xff09;从棋盘左上角出发沿着边缘线从左上角走到右下角&#xff0c;总共有多少种走法&#xff0c;要求不能走回头路&#xff0c;即&#xff1a;只能往右和往下…