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中使用glob和rmtree删除目录子目录及所有文件的例子
Nov 21 Python
Python编码爬坑指南(必看)
Jun 10 Python
Python命令启动Web服务器实例详解
Feb 23 Python
python中使用iterrows()对dataframe进行遍历的实例
Jun 09 Python
查看python下OpenCV版本的方法
Aug 03 Python
Django学习笔记之为Model添加Action
Apr 30 Python
Python使用import导入本地脚本及导入模块的技巧总结
Aug 07 Python
Python实现中值滤波去噪方式
Dec 18 Python
Python scrapy增量爬取实例及实现过程解析
Dec 24 Python
Python3爬虫里关于识别微博宫格验证码的知识点详解
Jul 30 Python
opencv实现图像平移效果
Mar 24 Python
教你如何使用Python下载B站视频的详细教程
Apr 29 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边学边教》(04.编写简易的通讯录――视频教程1)
2006/12/13 PHP
Discuz Uchome ajaxpost小技巧
2011/01/04 PHP
php切割页面div内容的实现代码分享
2012/07/31 PHP
laravel安装zend opcache加速器教程
2015/03/02 PHP
PHP单链表的实现代码
2016/07/05 PHP
Javascript中的for in循环和hasOwnProperty结合使用
2013/06/05 Javascript
Ext GridPanel加载完数据后进行操作示例代码
2014/06/17 Javascript
jQuery中get()方法用法实例
2014/12/27 Javascript
简述JavaScript的正则表达式中test()方法的使用
2015/06/16 Javascript
微信小程序实现多个按钮toggle功能的实例
2017/06/13 Javascript
js基于FileSaver.js 浏览器导出Excel文件的示例
2017/08/15 Javascript
JS基于for语句编写的九九乘法表示例
2018/01/04 Javascript
AngularJS动态添加数据并删除的实例
2018/02/27 Javascript
node实现的爬虫功能示例
2018/05/04 Javascript
element-ui table span-method(行合并)的实现代码
2018/12/20 Javascript
[02:44]DOTA2英雄基础教程 魅惑魔女
2014/01/07 DOTA
跟老齐学Python之for循环语句
2014/10/02 Python
Python获取文件ssdeep值的方法
2014/10/05 Python
在Python中使用SimpleParse模块进行解析的教程
2015/04/11 Python
Python实现求最大公约数及判断素数的方法
2015/05/26 Python
python基于隐马尔可夫模型实现中文拼音输入
2016/04/01 Python
python实现的AES双向对称加密解密与用法分析
2017/05/02 Python
对numpy中的where方法嵌套使用详解
2018/10/31 Python
处理Selenium3+python3定位鼠标悬停才显示的元素
2019/07/31 Python
Python学习笔记之迭代器和生成器用法实例详解
2019/08/08 Python
浅谈pycharm使用及设置方法
2019/09/09 Python
给Python学习者的文件读写指南(含基础与进阶)
2020/01/29 Python
mac安装python3后使用pip和pip3的区别说明
2020/09/01 Python
详解CSS3媒体查询响应式布局bootstrap 框架原理实战(推荐)
2020/11/16 HTML / CSS
北京某公司的.net笔试题
2014/03/20 面试题
大专计算机个人求职的自我评价
2013/10/21 职场文书
咖啡书吧创业计划书
2014/01/13 职场文书
大学英语演讲稿范文
2014/04/24 职场文书
建设单位项目负责人任命书
2014/06/06 职场文书
手术室消毒隔离制度
2015/08/05 职场文书
2019年二手房买卖合同范本
2019/10/14 职场文书