BeautifulSoup中find和find_all的使用详解


Posted in Python onDecember 07, 2020

爬虫利器BeautifulSoup中find和find_all的使用方法

二话不说,先上段HTML例子

<html>
  <head>
    <title>
      index
    </title>
  </head>
  <body>
     <div>
        <ul>
           <li id="flask"class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>
          <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>
          <li class="item-inactie"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>
          <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>
          <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a>
         </ul>
     </div>
    <li> hello world </li>
  </body>
</html>

使用BeautifulSoup前需要先构建BeautifulSoup实例

# 构建beautifulsoup实例
soup = BeautifulSoup(html,'lxml')
# 第一个参数是要匹配的内容
# 第二个参数是beautifulsoup要采用的模块,即规则

需要注意的是,导入对的模块需要事先安装,此处导入的LXML事先已经安装。可以导入的模块可通过查询BeautifulSoup的文档查看

BeautifulSoup中find和find_all的使用详解

接下来是find和find_all的介绍

1. find
只返回第一个匹配到的对象
语法:

find(name, attrs, recursive, text, **wargs)

# recursive 递归的,循环的

BeautifulSoup中find和find_all的使用详解

参数:

参数名 作用
name 查找标签
text 查找文本
attrs 基于attrs参数

例子:

# find查找一次
li = soup.find('li')
print('find_li:',li)
print('li.text(返回标签的内容):',li.text)
print('li.attrs(返回标签的属性):',li.attrs)
print('li.string(返回标签内容为字符串):',li.string)

运行结果:

find_li: <li class="item-0" id="flask"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>
li.text(返回标签的内容): first item
li.attrs(返回标签的属性): {'id': 'flask', 'class': ['item-0']}
li.string(返回标签内容为字符串): first item

find也可以通过‘属性=值'的方法进行匹配

li = soup.find(id = 'flask')
print(li,'\n')
<li class="item-0" id="flask"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>

需要注意的是,因为class是python的保留关键字,若要匹配标签内class的属性,需要特殊的方法,有以下两种:

  • 在attrs属性用字典的方式进行参数传递
  • BeautifulSoup自带的特别关键字class_
# 第一种:在attrs属性用字典进行传递参数
find_class = soup.find(attrs={'class':'item-1'})
print('findclass:',find_class,'\n')
# 第二种:BeautifulSoup中的特别关键字参数class_
beautifulsoup_class_ = soup.find(class_ = 'item-1')
print('BeautifulSoup_class_:',beautifulsoup_class_,'\n')

运行结果

findclass: <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>

BeautifulSoup_class_: <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>

2. find_all

返回所有匹配到的结果,区别于find(find只返回查找到的第一个结果)

语法:

find_all(name, attrs, recursive, text, limit, **kwargs)

BeautifulSoup中find和find_all的使用详解

参数名 作用
name 查找标签
text 查找文本
attrs 基于attrs参数

与find一样的语法

上代码

# find_all 查找所有
li_all = soup.find_all('li')
for li_all in li_all:
	print('---')
	print('匹配到的li:',li_all)
	print('li的内容:',li_all.text)
	print('li的属性:',li_all.attrs)

运行结果:

---
匹配到的li: <li class="item-0" id="flask"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>
li的内容: first item
li的属性: {'id': 'flask', 'class': ['item-0']}
---
匹配到的li: <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>
li的内容: second item
li的属性: {'class': ['item-1']}
---
匹配到的li: <li cvlass="item-inactie"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>
li的内容: third item
li的属性: {'cvlass': 'item-inactie'}
---
匹配到的li: <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>
li的内容: fourth item
li的属性: {'class': ['item-1']}
---
匹配到的li: <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a>
</li>
li的内容: fifth item

附上比较灵活的find_all查询方法:

# 最灵活的使用方式
li_quick = soup.find_all(attrs={'class':'item-1'})
for li_quick in li_quick:
	print('最灵活的查找方法:',li_quick)

运行结果:

  • 最灵活的查找方法: <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>
  • 最灵活的查找方法: <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>

完整代码:

# coding=utf8
# @Author= CaiJunxuan
# @QQ=469590490
# @Wechat:15916454524

# beautifulsoup

# 导入beautifulsoup模块
from bs4 import BeautifulSoup

# HTML例子
html = '''
<html>
  <head>
    <title>
      index
    </title>
  </head>
  <body>
     <div>
        <ul>
           <li id="flask"class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>
          <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>
          <li cvlass="item-inactie"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>
          <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>
          <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a>
         </ul>
     </div>
    <li> hello world </li>
  </body>
</html>
'''

# 构建beautifulsoup实例
soup = BeautifulSoup(html,'lxml')
# 第一个参数是要匹配的内容
# 第二个参数是beautifulsoup要采用的模块,即规则
# html.parser是python内置的结构匹配方法,但是效率不如lxml所以不常用
# lxml 采用lxml模块
# html5lib,该模块可以将内容转换成html5对象
# 若想要以上功能,就需要具备对应的模块,比如使用lxml就要安装lxml

# 在bs4当中有很多种匹配方法,但常用有两种:

# find查找一次
li = soup.find('li')
print('find_li:',li)
print('li.text(返回标签的内容):',li.text)
print('li.attrs(返回标签的属性):',li.attrs)
print('li.string(返回标签内容为字符串):',li.string)
print(50*'*','\n')

# find可以通过'属性 = 值'的方法进行select
li = soup.find(id = 'flask')
print(li,'\n')
# 因为class是python的保留关键字,所以无法直接查找class这个关键字
# 有两种方法可以进行class属性查询
# 第一种:在attrs属性用字典进行传递参数
find_class = soup.find(attrs={'class':'item-1'})
print('findclass:',find_class,'\n')
# 第二种:BeautifulSoup中的特别关键字参数class_
beautifulsoup_class_ = soup.find(class_ = 'item-1')
print('BeautifulSoup_class_:',beautifulsoup_class_,'\n')

# find_all 查找所有
li_all = soup.find_all('li')
for li_all in li_all:
	print('---')
	print('匹配到的li:',li_all)
	print('li的内容:',li_all.text)
	print('li的属性:',li_all.attrs)

# 最灵活的使用方式
li_quick = soup.find_all(attrs={'class':'item-1'})
for li_quick in li_quick:
	print('最灵活的查找方法:',li_quick)

到此这篇关于BeautifulSoup中find和find_all的使用详解的文章就介绍到这了,更多相关BeautifulSoup find和find_all内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
粗略分析Python中的内存泄漏
Apr 23 Python
简单谈谈Python中的闭包
Nov 30 Python
Python实现字符串匹配算法代码示例
Dec 05 Python
快速解决pandas.read_csv()乱码的问题
Jun 15 Python
Python从单元素字典中获取key和value的实例
Dec 31 Python
Python for循环与range函数的使用详解
Mar 23 Python
详解Python计算机视觉 图像扭曲(仿射扭曲)
Mar 27 Python
python中下标和切片的使用方法解析
Aug 27 Python
关于Python核心框架tornado的异步协程的2种方法详解
Aug 28 Python
python中shell执行知识点
May 06 Python
python批量提取图片信息并保存的实现
Feb 05 Python
深入理解pytorch库的dockerfile
Jun 10 Python
python爬虫beautifulsoup解析html方法
Dec 07 #Python
python可视化 matplotlib画图使用colorbar工具自定义颜色
Dec 07 #Python
用ldap作为django后端用户登录验证的实现
Dec 07 #Python
Django中使用Celery的方法步骤
Dec 07 #Python
python集合的新增元素方法整理
Dec 07 #Python
python进行二次方程式计算的实例讲解
Dec 06 #Python
paramiko使用tail实时获取服务器的日志输出详解
Dec 06 #Python
You might like
怎样在PHP中通过ADO调用Asscess数据库和COM程序
2006/10/09 PHP
php 日期和时间的处理-郑阿奇(续)
2011/07/04 PHP
学习php设计模式 php实现适配器模式
2015/12/07 PHP
javascript 设置文本框中焦点的位置
2009/11/20 Javascript
js获取浏览器的可视区域尺寸的实现代码
2011/11/30 Javascript
JavaScript/Js脚本处理html元素的自定义属性解析(亲测兼容Firefox与IE)
2013/11/25 Javascript
IE与FireFox的JavaScript兼容问题解决办法
2013/12/31 Javascript
JQuery实现动态添加删除评论的方法
2015/05/18 Javascript
JavaScript中的prototype原型学习指南
2016/05/09 Javascript
jQuery中的insertBefore(),insertAfter(),after(),before()区别介绍
2016/09/01 Javascript
JS实现表单多文件上传样式美化支持选中文件后删除相关项
2016/09/30 Javascript
vue实现全选和反选功能
2017/08/31 Javascript
JavaScript门道之标准库
2018/05/26 Javascript
详解webpack运行Babel教程
2018/06/13 Javascript
node.js通过Sequelize 连接MySQL的方法
2020/12/28 Javascript
python中常用检测字符串相关函数汇总
2015/04/15 Python
Python批量创建迅雷任务及创建多个文件
2016/02/13 Python
Python排序搜索基本算法之选择排序实例分析
2017/12/09 Python
Python之pandas读写文件乱码的解决方法
2018/04/20 Python
对python修改xml文件的节点值方法详解
2018/12/24 Python
如何通过雪花算法用Python实现一个简单的发号器
2019/07/03 Python
Python多线程爬取豆瓣影评API接口
2019/10/22 Python
Python request使用方法及问题总结
2020/04/26 Python
详解python程序中的多任务
2020/09/16 Python
欧缇丽美国官网:Caudalie美国
2016/12/31 全球购物
联想中国官方商城:Lenovo China
2017/10/18 全球购物
洛佩桑酒店官方网站:Lopesan Hotels
2019/04/15 全球购物
旅游饭店管理专业自荐书
2014/06/28 职场文书
过程装备与控制工程专业求职信
2014/07/02 职场文书
公文格式,规则明细(新手收藏)
2019/07/23 职场文书
go 实现简易端口扫描的示例
2021/05/22 Golang
Jupyter Notebook内使用argparse报错的解决方案
2021/06/03 Python
python使用pymysql模块操作MySQL
2021/06/16 Python
MySQL和Oracle批量插入SQL的通用写法示例
2021/11/17 MySQL
python数据可视化使用pyfinance分析证券收益示例详解
2021/11/20 Python
vue elementUI批量上传文件
2022/04/26 Vue.js