Python爬虫-BeautifulSoup解析

2024-04-28 19:04

本文主要是介绍Python爬虫-BeautifulSoup解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.简介

BeautifulSoup 是一个用于解析 HTML 和 XML 文档的 Python 库。它提供了一种灵活且方便的方式来导航、搜索和修改树结构或标记文档。这个库非常适合网页抓取和数据提取任务,因为它允许你以非常直观的方式查询和操作文档内容。

2.安装 Beautiful Soup

终端输入:pip install beautifulsoup4

3.四个关键对象-覆盖了HTML或XML的所有内容

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

3.1 BeatifulSoup对象

BeautifulSoup 对象在 BeautifulSoup 库中是一个特殊的对象,它代表了一个被解析的 HTML 或 XML 文档的整体内容。

我们可以使用BeautifulSoup方法实例化一个BeatifulSoup对象,接下来查看此对象的类型

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>
"""
from bs4 import BeautifulSoup
#这里,html_doc是你想要解析的HTML文档字符串,'html.parser'是解析器,它告诉BeautifulSoup使用Python的标准库来解析文档。
soup = BeautifulSoup(html_doc,'html.parser')
print(type(soup))

3.2 tag对象

tag对象与XML或HTML原生文档中的tag相同,我们可以使用BeautifulSoup对象来获取到tag对象。

通过tag对象获取属性值,方式:标签名['属性名'],示例如下:

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>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,'html.parser')
tag=soup.p#获取tag对象,当有多个同名标签,这种获取方式只会获取第一个
print(type(tag))
print(tag['class'])#获取指定属性值

当然属性值可能会有多个,HTML 4定义了一系列可以包含多个值的属性.在HTML5中移除了一些,却增加更多.最常见的多值的属性是 class (一个tag可以有多个CSS的class). 还有一些属性 rel , rev , accept-charset , headers , accesskey . 在Beautiful Soup中多值属性的返回类型是list,如果某个属性看起来好像有多个值,但在任何版本的HTML定义中都没有被定义为多值属性,那么Beautiful Soup会将这个属性作为字符串返回,实例如下:

html_doc = """
<html><head><title>The Dormouse's story</title></head><body>
<p class="title test" id="title test"><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>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,'html.parser')
tag=soup.p#获取tag对象
print(tag['class'])#获取指定属性值
print(tag['id'])

3.3 NavigableString对象

NavigableString 是 BeautifulSoup 库中的一个类,用于表示 HTML 或 XML 文档中的纯文本字符串,我们可以使用此对象获取标签中的值,获取方式为tag.string获取NavigableString对象,示例如下:

html_doc = """
<html><head><title>The Dormouse's story</title></head><body>
<p class="title test" id="title test"><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>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,'html.parser')
tag=soup.p#获取tag对象
print(tag.string,type(tag.string))

3.4 Comment对象

 对象是一个特殊类型的 NavigableString 对象,他可用来表示注释内容

html_doc = """
<html><head><title>The Dormouse's story</title></head><body>
<p class="title test" id="title test"><!--<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>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,'html.parser')
tag=soup.p#获取tag对象
print(tag.string,type(tag.string))

Beautiful Soup中定义的其它类型都可能会出现在XML的文档中: CData , ProcessingInstruction , Declaration , Doctype . Comment 对象类似,这些类都是 NavigableString 的子类,只是添加了一些额外的方法的字符串独享。

4.搜索文档树

搜索文档实际上是通过过滤器来实现的,这种过滤器类似于条件查询,过滤器可以被用在tag的name中,节点的属性中,字符串中或他们的混合中。

4.1 find_all方法

find_all方法法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件,当查询结果有多项时返回list列表。这是方法中的参数,下列是对这些参数的使用:

按属性查找
from bs4 import BeautifulSouphtml_doc = """  
<html><head><title>网站标题</title></head>  
<body>  
<p class="title"><b>第一个段落</b></p>  
<p class="story">第二个段落。</p>  
<p class="story">第三个段落。</p>  
<p class="title"><b>第四个段落</b></p>  
</body>  
</html>  
"""soup = BeautifulSoup(html_doc, 'html.parser')# 查找所有 class 属性为 "title" 的标签
title_tags = soup.find_all(attrs={"class": "title"})
for tag in title_tags:print(tag)


按CSS选择器查找

from bs4 import BeautifulSouphtml_doc = """  
<html><head><title>网站标题</title></head>  
<body>  
<p class="title"><b>第一个段落</b></p>  
<p class="story">第二个段落。</p>  
<p class="story">第三个段落。</p>  
<p class="title"><b>第四个段落</b></p>  
</body>  
</html>  
"""soup = BeautifulSoup(html_doc, 'html.parser')# 使用 CSS 类选择器查找
title_tags = soup.find_all(class_="title")
for tag in title_tags:print(tag)
# 使用 CSS 属性选择器查找
tags_with_href = soup.find_all(attrs={"href": True})
for tag in tags_with_href:print(tag)

按文本内容查找

你可以通过 string 参数来根据标签中的文本内容查找元素。

html_doc = """  
<html><head><title>网站标题</title></head>  
<body>  
<p class="title"><b>第一个段落</b></p>  
<p class="story">第二个段落。</p>  
<p class="story">第三个段落。</p>  
<p class="title"><b>第四个段落</b></p>  
</body>  
</html>  
"""soup = BeautifulSoup(html_doc, 'html.parser')
# 查找包含特定文本的 <p> 标签
p_tags_with_text = soup.find_all('p', string="第二个段落。")
for tag in p_tags_with_text:print(tag)

使用正则表达式查找

你还可以使用正则表达式来匹配标签中的文本内容。

from bs4 import BeautifulSoup
import re
html_doc = """  
<html><head><title>网站标题</title></head>  
<body>  
<p class="title"><b>第一个段落</b></p>  
<p class="story">第2个段落。</p>  
<p class="story">第三个段落。</p>  
<p class="title"><b>第四个段落</b></p>  
</body>  
</html>  
"""soup = BeautifulSoup(html_doc, 'html.parser')
p_tags_with_numbers = soup.find_all('p', string=re.compile(r'\d'))#\d表示匹配到任意数字,r表示普通字符串
for tag in p_tags_with_numbers:print(tag)

限制返回结果数量

你可以使用 limit 参数来限制 find_all 方法返回的结果数量。

from bs4 import BeautifulSoup
import re
html_doc = """  
<html><head><title>网站标题</title></head>  
<body>  
<p class="title"><b>第一个段落</b></p>  
<p class="story">第2个段落。</p>  
<p class="story">第三个段落。</p>  
<p class="title"><b>第四个段落</b></p>  
</body>  
</html>  
"""soup = BeautifulSoup(html_doc, 'html.parser')
# 只查找前两个 <p> 标签
first_two_p_tags = soup.find_all('p', limit=2)
for tag in first_two_p_tags:print(tag)
 

4.2 find方法

find方法与find_all方法使用方式基本一致,但是他只会匹配到第一项。

4.结尾

BeautifulSoup是解析爬取数据的利器,但是往往我们在采集数据时会遇到许多的问题,比如说ip封禁,明显是网站进行了反爬处理:限制IP请求频率。这个时候,代理ip解决这类问题就十分有效。这里推荐一款最近发现的代理商家:协采云IP池。

这篇关于Python爬虫-BeautifulSoup解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/944012

相关文章

使用Python创建一个功能完整的Windows风格计算器程序

《使用Python创建一个功能完整的Windows风格计算器程序》:本文主要介绍如何使用Python和Tkinter创建一个功能完整的Windows风格计算器程序,包括基本运算、高级科学计算(如三... 目录python实现Windows系统计算器程序(含高级功能)1. 使用Tkinter实现基础计算器2.

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财