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上基于Markov链生成伪随机文本的教程
Apr 17 Python
Diango + uwsgi + nginx项目部署的全过程(可外网访问)
Apr 22 Python
Python Selenium 之关闭窗口close与quit的方法
Feb 13 Python
树莓派使用python-librtmp实现rtmp推流h264的方法
Jul 22 Python
Flask框架模板渲染操作简单示例
Jul 31 Python
python3文件复制、延迟文件复制任务的实现方法
Sep 02 Python
Python3 无重复字符的最长子串的实现
Oct 08 Python
python中seaborn包常用图形使用详解
Nov 25 Python
使用Python制作缩放自如的圣诞老人(圣诞树)
Dec 25 Python
Python sorted对list和dict排序
Jun 09 Python
基于Tensorflow的MNIST手写数字识别分类
Jun 17 Python
Python基于xlrd模块处理合并单元格
Jul 28 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
Drupal7中常用的数据库操作实例
2014/03/02 PHP
PHP中捕获超时事件的方法实例
2015/02/12 PHP
ThinkPHP模板Volist标签嵌套循环输出多维数组的方法
2016/03/23 PHP
PHP微信开发之查询微信精选文章
2016/06/23 PHP
php微信公众平台开发(三)订阅事件处理
2016/12/06 PHP
PHP智能识别收货地址信息实例
2019/01/05 PHP
javascript实现动态增加删除表格行(兼容IE/FF)
2007/04/02 Javascript
javascript设计模式 封装和信息隐藏(上)
2012/07/24 Javascript
Android中资源文件(非代码部分)的使用概览
2012/12/18 Javascript
使用jQuery实现图片遮罩半透明坠落遮挡
2015/03/16 Javascript
javascript点击按钮实现隐藏显示切换效果
2016/02/03 Javascript
JavaScript基于原型链的继承
2016/06/22 Javascript
JS获得多个同name 的input输入框的值的实现方法
2017/01/09 Javascript
JavaScript模块化之使用requireJS按需加载
2017/04/12 Javascript
vue.js中mint-ui框架的使用方法
2017/05/12 Javascript
微信JSSDK调用微信扫一扫功能的方法
2017/07/25 Javascript
jQuery条件分页 代替离线查询(附代码)
2017/08/17 jQuery
js常用正则表达式集锦
2019/05/17 Javascript
Python ORM框架SQLAlchemy学习笔记之安装和简单查询实例
2014/06/10 Python
一个基于flask的web应用诞生(1)
2017/04/11 Python
python实现图书馆研习室自动预约功能
2018/04/27 Python
Django+Ajax+jQuery实现网页动态更新的实例
2018/05/28 Python
Python语言检测模块langid和langdetect的使用实例
2019/02/19 Python
Python实现去除图片中指定颜色的像素功能示例
2019/04/13 Python
利用Python查看微信共同好友功能的实现代码
2019/04/24 Python
windows下的pycharm安装及其设置中文菜单
2020/04/23 Python
具有防紫外线功能的高性能钓鱼服装:Hook&Tackle
2018/08/16 全球购物
匈牙利最大的健身制造商和销售商:inSPORTline
2018/10/30 全球购物
会计师职业生涯规划范文
2014/02/18 职场文书
教师自我鉴定范文
2014/03/20 职场文书
广告宣传策划方案
2014/05/21 职场文书
我的中国心演讲稿
2014/09/04 职场文书
2015年行政执法工作总结
2015/05/23 职场文书
接触艺术对孩子学习思维有益
2019/08/06 职场文书
60条职场经典语录,总有一条能触动你的心
2019/08/21 职场文书
雄兵连:第三季先行图公开,天使恶魔联合,银河之力的新力量
2021/06/11 国漫