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池。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/5679.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Time_embedding采样的理解

简单概括&#xff0c;就是t越大&#xff0c;采样得到的点越分散&#xff0c;采样得到的点范围更广 一个简单的示例函数 def time_embedding(t, max_steps1000):frequency np.linspace(0, 1, max_steps)embeddings np.concatenate([np.sin(frequency * t * math.pi),np.cos(f…

【webrtc】RemoteAudioSource的创建线程

m98 代码&#xff1a;I:\webrtc m98_yjf\src\pc\rtp_transmission_manager.cc RtpTransmissionManager::CreateReceiver 在信令线程创建receiver receiver 是&#xff1a; rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>receiver;其实际…

可视化大屏在真实场景的效果,绝对震撼,不要再嘲笑其作用了

hello&#xff0c;我是大千UI工场&#xff0c;本地带来一批可视化大屏现场效果图&#xff0c;非常震撼&#xff0c;给大家带来身临其境的感受&#xff0c;欢迎关注点赞&#xff0c;有需求请私信。 有人可能会认为可视化大屏没有太多价值&#xff0c;可能是因为以下几个原因&am…

记录PR学习查漏补缺

记录PR学习查漏补缺 常用快捷键文件编辑素材序列标记字幕窗口帮助 效果基本3D高斯模糊查找边缘色彩颜色平衡超级键马赛克中间值变形稳定器 常用 快捷键 注意&#xff1a;比较常用的用红色字体显示 文件 快捷键作用Ctrl Alt N新建项目Ctrl O打开项目Ctrl I导入Ctrl S保存…

链表面试题1.

1&#xff0c;反转一个单链表 采用头插法即可 class Solution {public ListNode reverseList(ListNode head) {if(head null){return head;}ListNode cur head.next;head.next null;while(cur ! null){ListNode curN cur.next;cur.next head;head cur ;cur curN;}return …

WEB攻防-PHP特性-piwigoCMS审计实例

前置知识&#xff1a;PHP函数缺陷 测试环境 &#xff1a;piwigo CMS 漏洞URL&#xff1a; 漏洞文件位置&#xff1a;\include \functions_rate.inc.php 漏洞产生入口文件&#xff1a;/picture.php picture.php中接受了一个GET方法action参数&#xff0c;作为switch...case.…

【Java探索之旅】包管理精粹 Java中包的概念与实践

文章目录 &#x1f4d1;前言一、封装1.1 封装的概念1.2 访问限定修饰符 二、封装扩展&#xff08;包&#xff09;2.1 包的概念2.2 带入包中的类2.3 自定义包2.4 常见的包 &#x1f324;️全篇总结 &#x1f4d1;前言 在Java编程中&#xff0c;封装是面向对象编程的核心概念之一…

知识产权 | 守护科技创新之光,共筑知识产权长城

2024年4月26日&#xff0c;迎来了一年一度的世界知识产权日&#xff0c;今年的主题是&#xff1a;“立足创新创造&#xff0c;构建共同未来。” 易我科技是一家专注于数据安全产品研发、生产、销售、服务一体化的高新技术软件企业。易我科技自成立以来&#xff0c;始终秉持尊重…

树莓派4B安装安卓系统LineageOS 21(Android14)

1&#xff1a;系统下载 2&#xff1a;下载好镜像后&#xff0c;准备写入SD卡&#xff0c;我这边使用的是 balenaetcher 3&#xff1a;插入树莓派&#xff0c;按照指示一步一步进行配置&#xff0c;可以配置时区&#xff0c;语言。 注意点 1》:想返回的时候按F2 2》:进入系统…

Redisson分布式锁,重试锁和锁续命的原理

RedissonLock 锁重试原理 tryLock有三个三个参数&#xff0c;第一个是等待时间&#xff0c;第二个是锁失效后自动释放的时间,不填默认为-1&#xff0c;第三个是时间单位&#xff1b; 当设置了第一个参数&#xff0c;那这个锁就成了可重试锁&#xff1b;获取锁失败后&#xff0c…

C++的演变与未来:编程艺术的持续进化

在计算机编程的演变历程中&#xff0c;C以其独特的魅力和强大的功能&#xff0c;一直占据着不可或缺的地位。从最初的面向对象编程&#xff0c;到如今的跨平台、高性能应用&#xff0c;C在不断地适应和推动着计算机技术的发展。本文将深入剖析C的演变过程&#xff0c;展望其未来…

C++ 优先级队列priority_queue

1、常用接口 底层使用的是堆实现&#xff0c;默认为大堆 2、理解&#xff1a; 优先级队列就是即使插入的是一个乱序的&#xff0c;但是依旧会按照有序的顺序出队列 优先级队列就是会根据大小来出队列&#xff0c;而不是谁在队头就出谁。 优先级队列底层是使用堆实现&#x…

Java项目:基于SSM框架实现的实践项目管理系统(ssm+B/S架构+源码+数据库+毕业论文+开题报告)

一、项目简介 本项目是一套基于SSM框架实现的实践项目管理系统&#xff0c;主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff…

【前端】-【防止接口重复请求】

文章目录 需求实现方案方案一方案二方案三 需求 对整个的项目都做一下接口防止重复请求的处理 实现方案 方案一 思路&#xff1a;通过使用axios拦截器&#xff0c;在请求拦截器中开启全屏Loading&#xff0c;然后在响应拦截器中将Loading关闭。 代码&#xff1a; 问题&…

Coursera: An Introduction to American Law 学习笔记 Week 04: Constitutional Law

An Introduction to American Law 本文是 https://www.coursera.org/programs/career-training-for-nevadans-k7yhc/learn/american-law 这门课的学习笔记。 文章目录 An Introduction to American LawInstructors Week 04: Constitutional LawKey Constitutional Law TermsSup…

黑马 - websocket搭建在线聊天室

这里写自定义目录标题 一、消息推送常见方式二、websocket 是什么&#xff1f;三、websocket api的介绍1、客户端 &#xff08;浏览器&#xff09; 四、实现在线聊天室1、需求2、聊天室流程分析3、消息格式4、代码实现 一、消息推送常见方式 1、轮训方式 2、SSE&#xff08;…

2024年第二十一届 五一杯 (A题)大学生数学建模挑战赛 | 多目标优化问题,深度学习分析 | 数学建模完整代码解析

DeepVisionary 每日深度学习前沿科技推送&顶会论文&数学建模与科技信息前沿资讯分享&#xff0c;与你一起了解前沿科技知识&#xff01; 本次DeepVisionary带来的是五一杯的详细解读&#xff1a; 完整内容可以在文章末尾全文免费领取&阅读&#xff01; 第一个问题…

【Linux】进程终止

思维导图 学习内容 进程终止是进程控制里面的一个重要的知识&#xff0c;通过这一篇博客&#xff0c;我们可以学习到进程终止的概念&#xff0c;进程终止的三种情况&#xff0c;进程终止的退出码和退出信号&#xff0c;最后在来学习进程是如何进行终止的。 学习目标 进程终止…

诺基亚贝尔探访上海斯歌,共探创新合作新机遇

近日&#xff0c;上海斯歌K2 BPM迎来重要客户考察交流活动。来自诺基亚贝尔的首席数字官刘少勇一行莅临了上海斯歌K2 BPM 的武汉研发中心&#xff0c;并对上海斯歌在BPM业务流程管理领域的研发成果及交付能力给予了高度肯定。 此次活动不仅加深了双方的战略合作&#xff0c;也为…

维修家政按摩到家上门小程序开源版开发

维修家政按摩到家上门小程序开源版开发 智能定位&#xff0c;精准计费——全新上门服务平台功能解析。 全新上门服务平台已经上线&#xff0c;它拥有一系列强大的功能&#xff0c;旨在为用户提供最便捷、最个性化的服务体验。 !](https://img-blog.csdnimg.cn/direct/86195e…