BeautifulSoup文档4-详细方法 | 用什么方法对文档树进行搜索?
4-详细方法 | 用什么方法对文档树进行搜索?
- 1 过滤器
- 1.1 字符串
- 1.2 正则表达式
- 1.3 列表
- 1.4 True
- 1.5 可以自定义方法
- 2 find_all()
- 2.1 参数原型
- 2.2 name参数
- 2.3 keyword 参数
- 2.4 string 参数
- 2.5 limit 参数
- 2.6 recursive 参数
- 3 find()
- 4 find_parents()和find_parent()
- 5 find_next_siblings() 和 find_next_sibling()
- 6 find_previous_siblings() 和 find_previous_sibling()
- 7 find_all_next() 和 find_next()
- 8 find_all_previous() 和 find_previous()
- 9 本文涉及的源码
BeautifulSoup
的文档搜索方法有很多,官方文档中重点介绍了两个方法:
find() 和 find_all()
- 下文中的实例,依旧是官网的例子:
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')
1 过滤器
- 在介绍文档搜索方法之前,先了解下各种过滤器。
1.1 字符串
- 即在搜索方法中传如一个字符串参数;
BeautifulSoup
会查找与字符串完全匹配的内容;- 如查找
b
标签:
print(soup.find_all('b'))
- 输出为:
[<b>The Dormouse's story</b>]
1.2 正则表达式
- 传入正则表达式作为参数;
Beautiful Soup
会通过正则表达式的match()
来匹配内容;- 如找出所有以
b
开头的标签:
import re
for tag in soup.find_all(re.compile("^b")):print(tag.name)
- 输出为:
body
b
1.3 列表
- 传入列表参数;
Beautiful Soup
会将与列表中任一元素匹配的内容返回;- 如找到文档中所有
a
标签和b
标签:
print(soup.find_all(["a", "b"]))
- 输出为:
[<b>The Dormouse's story</b>,
<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>]
1.4 True
True
可以匹配任何值;- 如查找到所有的
tag
:
for tag in soup.find_all(True):print(tag.name)
- 输出为:
html
head
title
body
p
b
p
a
a
a
p
1.5 可以自定义方法
- 如果没有合适过滤器,那么还可以定义一个方法;
- 方法只接受一个元素参数;
- 如果这个方法返回
True
表示当前元素匹配并且被找到,如果不是则反回False
;
2 find_all()
- 搜索当前
tag
的所有tag
子节点,并判断是否符合过滤器的条件。 - 比如:
print(soup.find_all("title"))
- 输出为:
[<title>The Dormouse's story</title>]
2.1 参数原型
find_all( name , attrs , recursive , string , **kwargs )
2.2 name参数
- 查找所有名字为
name
的tag
; - 如:
print(soup.find_all("title"))
,输出为:[<title>The Dormouse's story</title>]
。
2.3 keyword 参数
- 如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字
tag
的属性来搜索; - 如:
print(soup.find_all(id='link2'))
,输出为:
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
- 按照
CSS
搜索,可以通过class_
参数搜索有指定CSS
类名的tag
; - 如:
print(soup.find_all("a", class_="sister"))
,输出为:
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</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>]
2.4 string 参数
- 通过
string
参数可以搜文档中的字符串内容.
与name
参数的可选值一样; - 如:
print(soup.find_all(string="Elsie"))
,输出为:['Elsie']
;
2.5 limit 参数
- 可以使用
limit
参数限制搜索返回结果的数量,避免返回结果很大速度很慢; - 如:
soup.find_all("a", limit=2)
,输出为:
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
2.6 recursive 参数
- 只搜索
tag
的直接子节点,可以使用参数recursive=False
; - 如:
<html><head><title>The Dormouse's story</title></head>
...
- 不使用
recursive
参数:
print(soup.html.find_all("title"))
- 输出为:
[<title>The Dormouse's story</title>]
- 使用
recursive
参数:
print(soup.html.find_all("title", recursive=False))
- 输出为:
[]
3 find()
find_all()
方法的返回结果是值包含一个元素的列表,而find()
方法直接返回结果;find_all()
方法没有找到目标是返回空列表,find()
方法找不到目标时,返回None
。- 如:
print(soup.find("nosuchtag"))
,输出为:None
。 - 参数原型:
find( name , attrs , recursive , string , **kwargs )
4 find_parents()和find_parent()
- 参数原型:
find_parents( name , attrs , recursive , string , **kwargs )
find_parent( name , attrs , recursive , string , **kwargs )
find_parents() 和 find_parent()
用来搜索当前节点的父辈节点;find_all() 和 find()
只搜索当前节点的所有子节点,孙子节点等;- 如:
a_string = soup.find(string="Lacie")
print(a_string)
print(a_string.find_parents("a"))
- 输出为:
Lacie
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
5 find_next_siblings() 和 find_next_sibling()
- 参数原型:
find_next_siblings( name , attrs , recursive , string , **kwargs )
find_next_sibling( name , attrs , recursive , string , **kwargs )
- 这2个方法通过
.next_siblings
属性对当tag
的所有后面解析的兄弟tag
节点进行迭代; find_next_siblings()
方法返回所有符合条件的后面的兄弟节点;find_next_sibling()
只返回符合条件的后面的第一个tag
节点;- 如:
first_link = soup.a
print(first_link)
print(first_link.find_next_siblings("a"))
first_story_paragraph = soup.find("p", "story")
print(first_story_paragraph.find_next_sibling("p"))
- 输出为:
<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>]
<p class="story">...</p>
6 find_previous_siblings() 和 find_previous_sibling()
- 参数原型:
find_previous_siblings( name , attrs , recursive , string , **kwargs )
find_previous_sibling( name , attrs , recursive , string , **kwargs )
- 这2个方法通过
.previous_siblings
属性对当前tag
的前面解析的兄弟tag
节点进行迭代; find_previous_siblings()
方法返回所有符合条件的前面的兄弟节点;find_previous_sibling()
方法返回第一个符合条件的前面的兄弟节点。
7 find_all_next() 和 find_next()
- 参数原型:
find_all_next( name , attrs , recursive , string , **kwargs )
find_next( name , attrs , recursive , string , **kwargs )
- 这2个方法通过
.next_elements
属性对当前tag的之后的tag
和字符串进行迭代; find_all_next()
方法返回所有符合条件的节点;find_next()
方法返回第一个符合条件的节点。
8 find_all_previous() 和 find_previous()
- 参数原型:
find_all_previous( name , attrs , recursive , string , **kwargs )
find_previous( name , attrs , recursive , string , **kwargs )
- 这2个方法通过
.previous_elements
属性对当前节点前面的tag
和字符串进行迭代; find_all_previous()
方法返回所有符合条件的节点;find_previous()
方法返回第一个符合条件的节点。
9 本文涉及的源码
# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2023/2/17
# 文件名称:bs04.py
# 作用:beautifulsoup的应用
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelsonfrom bs4 import BeautifulSouphtml_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>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# ====== 过滤器 ======
# 字符串
print(soup.find_all('b'))
# 正则表达式
import re
for tag in soup.find_all(re.compile("^b")):print(tag.name)
# 列表
print(soup.find_all(["a", "b"]))
# True
for tag in soup.find_all(True):print(tag.name)# ====== find_all() ======
print(soup.find_all("title"))
print(soup.find_all(id='link2'))
print(soup.find_all("a", class_="sister"))
print(soup.find_all(string="Elsie"))
print(soup.find_all("a", limit=2))
print(soup.html.find_all("title", recursive=False))# ====== find() ======
print(soup.find("nosuchtag"))
a_string = soup.find(string="Lacie")
print(a_string)
print(a_string.find_parents("a"))
first_link = soup.a
print(first_link)
print(first_link.find_next_siblings("a"))
first_story_paragraph = soup.find("p", "story")
print(first_story_paragraph.find_next_sibling("p"))
相关文章:
BeautifulSoup文档4-详细方法 | 用什么方法对文档树进行搜索?
4-详细方法 | 用什么方法对文档树进行搜索?1 过滤器1.1 字符串1.2 正则表达式1.3 列表1.4 True1.5 可以自定义方法2 find_all()2.1 参数原型2.2 name参数2.3 keyword 参数2.4 string 参数2.5 limit 参数2.6 recursive 参数3 find()4 find_parents()和find_parent()5…...
初识Tkinter界面设计
目录 前言 一、初识Tkinter 二、Label控件 三、Button控件 四、Entry控件 前言 本文简单介绍如何使用Python创建一个界面。 一、初识Tk...

软件测试面试题中的sql题目你会做吗?
目录 1.学生表 2.一道SQL语句面试题,关于group by表内容: 3.表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列,当B列大于C列时选择B列否则选择C列 4. 5.姓名:name 课程:subject 分数&…...

VS实用调试技巧
一.什么是BUG🐛Bug一词的原意是虫子,而在电脑系统或程序中隐藏着的一些未被发现的缺陷或问题,人们也叫它"bug"。这是为什么呢?这就要追溯到一个程序员与飞蛾的故事了。Bug的创始人格蕾丝赫柏(Grace Murray H…...

通俗易懂理解三次握手、四次挥手(TCP)
文章目录1、通俗语言理解1.1 三次握手1.2 四次挥手2、进一步理解三次握手和四次挥手2.1 三次握手2.2 四次挥手1、通俗语言理解 1.1 三次握手 C:客户端 S:服务器端 第一次握手: C:在吗?我要和你建立连接。 第二次握手ÿ…...

1.1 什么是并发
1.1 什么是并发 并发:指两个或更多独立的活动同时发生。并发在生活中随处可见。我们可以一边走路一边说话,也可以两只手同时做不同的动作。 1.1.1 计算机系统中的并发 当我们提到计算机术语的“并发”,指的是在单个系统里同时执行多个独立…...

万字讲解你写的代码是如何跑起来的?
今天我们来思考一个简单的问题,一个程序是如何在 Linux 上执行起来的? 我们就拿全宇宙最简单的 Hello World 程序来举例。 #include <stdio.h> int main() {printf("Hello, World!\n");return 0; } 我们在写完代码后,进行…...
034.Solidity入门——21不可变量
Solidity 中的不可变量是在编译时就被确定的常量,也称为常量变量(constant variable)或只读变量(read-only variable)。这些变量在定义时必须立即初始化,并且在整个合约中都无法被修改,可以在函…...

Vulnhub 渗透练习(四)—— Acid
环境搭建 环境下载 kail 和 靶机网络适配调成 Nat 模式,实在不行直接把网络适配还原默认值,再重试。 信息收集 主机扫描 没扫到,那可能端口很靠后,把所有端口全扫一遍。 发现 33447 端口。 扫描目录,没什么有用的…...
C++ 在线工具
online编译器https://godbolt.org/Online C Compiler - online editor (onlinegdb.com) https://www.onlinegdb.com/online_c_compilerC Shell (cpp.sh) https://cpp.sh/在线文档Open Standards (open-std.org)Index of /afs/cs.cmu.edu/academic/class/15211/spring.96/wwwC P…...

使用MMDetection进行目标检测、实例和全景分割
MMDetection 是一个基于 PyTorch 的目标检测开源工具箱,它是 OpenMMLab 项目的一部分。包含以下主要特性: 支持三个任务 目标检测(Object Detection)是指分类并定位图片中物体的任务实例分割(Instance Segmentation&a…...

使用ThreadLocal实现当前登录信息的存取
有志者,事竟成 文章持续更新,可以关注【小奇JAVA面试】第一时间阅读,回复【资料】获取福利,回复【项目】获取项目源码,回复【简历模板】获取简历模板,回复【学习路线图】获取学习路线图。 文章目录一、使用…...

高通平台开发系列讲解(Android篇)AudioTrack音频流数据传输
文章目录 一、音频流数据传输通道创建1.1、流程描述1.2、流程图解二、音频数据传输2.1、流程描述2.2、流程图解沉淀、分享、成长,让自己和他人都能有所收获!😄 📢本篇章主要图解AudioTrack音频流数据传输 。 一、音频流数据传输通道创建 1.1、流程描述 AudioTrack在set函…...

BUUCTF-firmware1
题目下载:下载 新题型,记录一下 题目给出了flag形式,md5{网址:端口},下载发现是一个.bin文件 二进制文件,其用途依系统或应用而定。一种文件格式binary的缩写。一个后缀名为".bin"的文件&#x…...

【C++之容器篇】二叉搜索树的理论与使用
目录前言一、二叉搜索树的概念二、二叉搜素树的模拟实现(增删查非递归实现)1. 二叉搜素树的结点2. 二叉搜索树的实现(1). 二叉搜索树的基本结构(2)构造函数(3)查找函数(4…...
爬虫神级解析工具之XPath:用法详解及实战
一、XPATH是什么 Xpath最初被设计用来搜寻XML文档,但它同样适用于HTML文档的搜索。通过简洁明了的路径选择表达式,它提供了强大的选择功能;同时得益于其内置的丰富的函数,它可以匹配和处理字符串、数值、时间等数据格式,几乎所有节点我们都可以通过Xpath来定位。 在Pyth…...
Markdown编辑器
这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注…...

数据结构<堆>
🎇🎇🎇作者: 小鱼不会骑车 🎆🎆🎆专栏: 《数据结构》 🎓🎓🎓个人简介: 一名专科大一在读的小比特,努力学习编程是我唯一…...

Linux下Socket编程利用多进程实现一台服务器与多台客户端并发通信
文章目录前言一、服务器 server二、客户端 client三、并发通信演示四、程序源码前言 前些日子同“ Linux应用编程 ”专栏中发布过的TCP及UDP在Linux或Windows下的通信都为单进程下的Socket编程,若还存在一些套接字相关函数模糊不清,读者可移步“Socket编…...

【MySQL】数据库基础
目录 1、什么是数据库 2、 数据库基本操作 2.1 查看当前数据库 2.2 创建一个数据库 2.3 选中数据库 2.4 删除数据库 3、常见的数据类型 3.1 数值类型 3.2 字符串类型 3.3 日期类型 4、表的操作 4.1 创建表 4.2 查看指定数据库下的所有表 4.3 查看表的结构 4.…...
【根据当天日期输出明天的日期(需对闰年做判定)。】2022-5-15
缘由根据当天日期输出明天的日期(需对闰年做判定)。日期类型结构体如下: struct data{ int year; int month; int day;};-编程语言-CSDN问答 struct mdata{ int year; int month; int day; }mdata; int 天数(int year, int month) {switch (month){case 1: case 3:…...

SCAU期末笔记 - 数据分析与数据挖掘题库解析
这门怎么题库答案不全啊日 来简单学一下子来 一、选择题(可多选) 将原始数据进行集成、变换、维度规约、数值规约是在以下哪个步骤的任务?(C) A. 频繁模式挖掘 B.分类和预测 C.数据预处理 D.数据流挖掘 A. 频繁模式挖掘:专注于发现数据中…...

DAY 47
三、通道注意力 3.1 通道注意力的定义 # 新增:通道注意力模块(SE模块) class ChannelAttention(nn.Module):"""通道注意力模块(Squeeze-and-Excitation)"""def __init__(self, in_channels, reduction_rat…...
TRS收益互换:跨境资本流动的金融创新工具与系统化解决方案
一、TRS收益互换的本质与业务逻辑 (一)概念解析 TRS(Total Return Swap)收益互换是一种金融衍生工具,指交易双方约定在未来一定期限内,基于特定资产或指数的表现进行现金流交换的协议。其核心特征包括&am…...

WordPress插件:AI多语言写作与智能配图、免费AI模型、SEO文章生成
厌倦手动写WordPress文章?AI自动生成,效率提升10倍! 支持多语言、自动配图、定时发布,让内容创作更轻松! AI内容生成 → 不想每天写文章?AI一键生成高质量内容!多语言支持 → 跨境电商必备&am…...
python报错No module named ‘tensorflow.keras‘
是由于不同版本的tensorflow下的keras所在的路径不同,结合所安装的tensorflow的目录结构修改from语句即可。 原语句: from tensorflow.keras.layers import Conv1D, MaxPooling1D, LSTM, Dense 修改后: from tensorflow.python.keras.lay…...
基于Java Swing的电子通讯录设计与实现:附系统托盘功能代码详解
JAVASQL电子通讯录带系统托盘 一、系统概述 本电子通讯录系统采用Java Swing开发桌面应用,结合SQLite数据库实现联系人管理功能,并集成系统托盘功能提升用户体验。系统支持联系人的增删改查、分组管理、搜索过滤等功能,同时可以最小化到系统…...

安宝特方案丨船舶智造的“AR+AI+作业标准化管理解决方案”(装配)
船舶制造装配管理现状:装配工作依赖人工经验,装配工人凭借长期实践积累的操作技巧完成零部件组装。企业通常制定了装配作业指导书,但在实际执行中,工人对指导书的理解和遵循程度参差不齐。 船舶装配过程中的挑战与需求 挑战 (1…...

【JVM面试篇】高频八股汇总——类加载和类加载器
目录 1. 讲一下类加载过程? 2. Java创建对象的过程? 3. 对象的生命周期? 4. 类加载器有哪些? 5. 双亲委派模型的作用(好处)? 6. 讲一下类的加载和双亲委派原则? 7. 双亲委派模…...

解读《网络安全法》最新修订,把握网络安全新趋势
《网络安全法》自2017年施行以来,在维护网络空间安全方面发挥了重要作用。但随着网络环境的日益复杂,网络攻击、数据泄露等事件频发,现行法律已难以完全适应新的风险挑战。 2025年3月28日,国家网信办会同相关部门起草了《网络安全…...