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

相关文章

容器镜像安全管理解析

目录 1. 镜像的层次结构与安全性2. 安全扫描工具3. 安全的最佳实践4. 安全策略实施 镜像安全在容器化和云原生应用中至关重要,因为容器镜像通常包含了应用及其依赖的所有必要组件,任何安全漏洞都可能成为攻击的入口点。 1. 镜像的层次结构与安全性 容器镜像由多个可读写的层组成,每一层代表了一组文件系统的更改。这种设计虽然提高了构建和分发效率,但也意味着如果底层镜像含有安全漏洞

Android中解析JSON数据

文章目录 Json 介绍使用 JSONObject 解析 Json使用 GSON 解析 JsonFastjson Json 介绍 Json 是一种文本形式的数据交换格式,比起 XML,JSON 的主要优势在于它的体积更小,在网络上传输的时候可以更省流量。但缺点在于,它的语义性较差,看起来不如 XML 直观 使用 JSONObject 解析 Json 解析 Json 数据也有很

Python-VBA函数之旅-str函数

目录 一、str函数的常见应用场景 二、str函数使用注意事项 三、如何用好str函数? 1、str函数: 1-1、Python: 1-2、VBA: 2、推荐阅读: 个人主页: https://myelsa1024.blog.csdn.net/ 一、str函数的常见应用场景         str函数在Python中有着广泛的应用场景,主要用于将非字符串类型的对象转

python把png转成jpg

在Python中,你可以使用PIL(Python Imaging Library,也称为Pillow)库来读取PNG图片并将其转换为JPG格式。下面是一个简单的示例代码: from PIL import Image# 打开PNG图片png_image = Image.open('input.png')# 保存为JPG图片png_image.save('output.jpg', 'JPEG')

用 Python 和 AkShare 进行个股数据清洗:源码剖析和建议优化

这是《个股清洗源码》一个获取股票买卖盘信息并将其打印到控制台并保存到文件的脚本。 下面我们来对源码进行剖析 先复习一下源码 import osimport akshare as akfrom akshare import stock_bid_ask_emfrom datetime import datetimeimport pandas as pdfrom io import Str

Python实现通过GUI界面,进行自动化“网络监控”

前言 本文是该专栏的第47篇,后面会持续分享python的各种干货知识,值得关注。 在本专栏前面,笔者在在文章《Python实现自动进行网络监控》里面,有详细介绍通过python实现自动进行“网络监控”。而本文,笔者将该篇文章的基础上,将自动进行“网络监控”的功能,封装成一个GUI工具。换言之,通过在该GUI工具上进行操作,即可实现网络监控等功能。 具体细节部分,笔者在正文将结合实际完

算法学习012-不同路径 c++动态规划算法实现 中小学算法思维学习 信奥算法解析

目录 C++不同路径 一、题目要求 1、编程实现 2、输入输出 二、算法分析 三、程序编写 四、运行结果 五、考点分析 六、推荐资料 C++不同路径 一、题目要求 1、编程实现 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Fini

【Python】安装和第一个程序

文章目录 Python环境安装第一个python程序输出Hello world获取输入 python2和python3共存 Python环境安装 官网下载 当我们从Python官方网站下载并安装好Python 3.x后,我们就直接获得了一个官方版本的解释器:CPython。这个解释器是用C语言开发的,所以叫CPython。在命令行下运行python就是启动CPython解

SpringAI 技术解析

1. 发展历史         SpringAI 的发展历史可以追溯到对 Spring 框架的扩展和改进,以支持人工智能相关的功能。随着人工智能技术的快速发展,SpringAI 逐渐成为 Spring 生态系统中的一个重要组成部分,为开发者提供了便捷、灵活的解决方案。         项目的灵感来自著名的 Python 项目,如 LangChain 和 LlamaIndex,但 Spring

Python | Leetcode Python题解之第84题柱状图中最大的矩形

题目: 题解: class Solution:def largestRectangleArea(self, heights: List[int]) -> int:n = len(heights)left, right = [0] * n, [n] * nmono_stack = list()for i in range(n):while mono_stack and heights[mon