详解Python利用Beautiful Soup模块搜索内容方法
这篇文章主要给大家介绍了python中 Beautiful Soup 模块的搜索方法函数。 方法不同类型的过滤参数能够进行不同的过滤,得到想要的结果。文中介绍的非常详细,对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
前言
我们将利用 Beautiful Soup 模块的搜索功能,根据标签名称、标签属性、文档文本和正则表达式来搜索。
搜索方法
Beautiful Soup 内建的搜索方法如下:
find()
find_all()
find_parent()
find_parents()
find_next_sibling()
find_next_siblings()
find_previous_sibling()
find_previous_siblings()
find_previous()
find_all_previous()
find_next()
find_all_next()
使用 find() 方法搜索
首先还是需要建立一个 HTML 文件用来做测试。
<html> <body> <p class="ecopyramid"> <ul id="producers"> <li class="producerlist"> <p class="name">plants</p> <p class="number">100000</p> </li> <li class="producerlist"> <p class="name">algae</p> <p class="number">100000</p> </li> </ul> <ul id="primaryconsumers"> <li class="primaryconsumerlist"> <p class="name">deer</p> <p class="number">1000</p> </li> <li class="primaryconsumerlist"> <p class="name">rabbit</p> <p class="number">2000</p> </li> </ul> <ul id="secondaryconsumers"> <li class="secondaryconsumerlist"> <p class="name">fox</p> <p class="number">100</p> </li> <li class="secondaryconsumerlist"> <p class="name">bear</p> <p class="number">100</p> </li> </ul> <ul id="tertiaryconsumers"> <li class="tertiaryconsumerlist"> <p class="name">lion</p> <p class="number">80</p> </li> <li class="tertiaryconsumerlist"> <p class="name">tiger</p> <p class="number">50</p> </li> </ul> </p> </body> </html>
我们可以通过 find()
方法来获得
- 标签,默认情况下会得到第一个出现的。接着再获取
- 标签,默认情况下还是会得到第一个出现的,接着获得
标签,通过输出内容来验证是否获取了第一个出现的标签。
from bs4 import BeautifulSoup with open('search.html','r') as filename: soup = BeautifulSoup(filename,'lxml') first_ul_entries = soup.find('ul') print first_ul_entries.li.p.string
登录后复制find() 方法具体如下:
find(name,attrs,recursive,text,**kwargs)
登录后复制正如上代码所示,
find()
方法接受五个参数:name、attrs、recursive、text 和 **kwargs 。name 、attrs 和 text 参数都可以在find()
方法充当过滤器,提高匹配结果的精确度。搜索标签
除了上面代码的搜索
- 标签外,我们还可以搜索
- 标签,返回结果也是返回出现的第一个匹配内容。
tag_li = soup.find('li') # tag_li = soup.find(name = "li") print type(tag_li) print tag_li.p.string
登录后复制搜索文本
如果我们只想根据文本内容来搜索的话,我们可以只传入文本参数 :
search_for_text = soup.find(text='plants') print type(search_for_text) <class 'bs4.element.NavigableString'>
登录后复制返回的结果也是 NavigableString 对象 。
根据正则表达式搜索
如下的一段 HTML 文本内容
<p>The below HTML has the information that has email ids.</p> abc@example.com <p>xyz@example.com</p> <span>foo@example.com</span>
登录后复制可以看到 abc@example 邮件地址并没有包括在任何标签内,这样就不能根据标签来找到邮件地址了。这个时候,我们可以使用正则表达式来进行匹配。
email_id_example = """ <p>The below HTML has the information that has email ids.</p> abc@example.com <p>xyz@example.com</p> <span>foo@example.com</span> """ email_soup = BeautifulSoup(email_id_example,'lxml') print email_soup # pattern = "\w+@\w+\.\w+" emailid_regexp = re.compile("\w+@\w+\.\w+") first_email_id = email_soup.find(text=emailid_regexp) print first_email_id
登录后复制在使用正则表达式进行匹配时,如果有多个匹配项,也是先返回第一个。
根据标签属性值搜索
可以通过标签的属性值来搜索:
search_for_attribute = soup.find(id='primaryconsumers') print search_for_attribute.li.p.string
登录后复制根据标签属性值来搜索对大多数属性都是可用的,例如:id、style 和 title 。
但是对以下两种情况会有不同:
自定义属性
类 ( class ) 属性
我们不能再直接使用属性值来搜索了,而是得使用 attrs 参数来传递给
find()
函数。根据自定义属性来搜索
在 HTML5 中是可以给标签添加自定义属性的,例如给标签添加 属性。
如下代码所示,如果我们再像搜索 id 那样进行操作的话,会报错的,Python 的变量不能包括 - 符号。
customattr = """ <p data-custom="custom">custom attribute example</p> """ customsoup = BeautifulSoup(customattr,'lxml') customsoup.find(data-custom="custom") # SyntaxError: keyword can't be an expression
登录后复制这个时候使用 attrs 属性值来传递一个字典类型作为参数进行搜索:
using_attrs = customsoup.find(attrs={'data-custom':'custom'}) print using_attrs
登录后复制基于 CSS 中的 类 进行搜索
对于 CSS 的类属性,由于在 Python 中 class 是个关键字,所以是不能当做标签属性参数传递的,这种情况下,就和自定义属性一样进行搜索。也是使用 attrs 属性,传递一个字典进行匹配 。
除了使用 attrs 属性之外,还可以使用 class_ 属性进行传递,这样与 class 区别开了,也不会导致错误。
css_class = soup.find(attrs={'class':'producerlist'}) css_class2 = soup.find(class_ = "producerlist") print css_class print css_class2
登录后复制使用自定义的函数搜索
可以给
find()
方法传递一个函数,这样就会根据函数定义的条件进行搜索。函数应该返回 true 或者是 false 值。
def is_producers(tag): return tag.has_attr('id') and tag.get('id') == 'producers' tag_producers = soup.find(is_producers) print tag_producers.li.p.string
登录后复制代码中定义了一个 is_producers 函数,它将检查标签是否具体 id 属性以及属性值是否等于 producers,如果符合条件则返回 true ,否则返回 false 。
联合使用各种搜索方法
Beautiful Soup 提供了各种搜索方法,同样,我们也可以联合使用这些方法来进行匹配,提高搜索的准确度。
combine_html = """ <p class="identical"> Example of p tag with class identical </p> <p class="identical"> Example of p tag with class identical <p> """ combine_soup = BeautifulSoup(combine_html,'lxml') identical_p = combine_soup.find("p",class_="identical") print identical_p
登录后复制使用 find_all() 方法搜索
使用
find()
方法会从搜索结果中返回第一个匹配的内容,而find_all()
方法则会返回所有匹配的项。在
find()
方法中用到的过滤项,同样可以用在find_all()
方法中。事实上,它们可以用到任何搜索方法中,例如:find_parents()
和find_siblings()
中 。# 搜索所有 class 属性等于 tertiaryconsumerlist 的标签。 all_tertiaryconsumers = soup.find_all(class_='tertiaryconsumerlist') print type(all_tertiaryconsumers) for tertiaryconsumers in all_tertiaryconsumers: print tertiaryconsumers.p.string
登录后复制find_all()
方法为 :find_all(name,attrs,recursive,text,limit,**kwargs)
登录后复制它的参数和
find()
方法有些类似,多个了 limit 参数。limit 参数是用来限制结果数量的。而find()
方法的 limit 就是 1 了。同时,我们也能传递一个字符串列表的参数来搜索标签、标签属性值、自定义属性值和 CSS 类。
# 搜索所有的 p 和 li 标签 p_li_tags = soup.find_all(["p","li"]) print p_li_tags print # 搜索所有类属性是 producerlist 和 primaryconsumerlist 的标签 all_css_class = soup.find_all(class_=["producerlist","primaryconsumerlist"]) print all_css_class print
登录后复制搜索相关标签
一般情况下,我们可以使用
find()
和find_all()
方法来搜索指定的标签,同时也能搜索其他与这些标签相关的感兴趣的标签。搜索父标签
可以使用
find_parent()
或者find_parents()
方法来搜索标签的父标签。find_parent()
方法将返回第一个匹配的内容,而find_parents()
将返回所有匹配的内容,这一点与find()
和find_all()
方法类似。# 搜索 父标签 primaryconsumers = soup.find_all(class_='primaryconsumerlist') print len(primaryconsumers) # 取父标签的第一个 primaryconsumer = primaryconsumers[0] # 搜索所有 ul 的父标签 parent_ul = primaryconsumer.find_parents('ul') print len(parent_ul) # 结果将包含父标签的所有内容 print parent_ul print # 搜索,取第一个出现的父标签.有两种操作 immediateprimary_consumer_parent = primaryconsumer.find_parent() # immediateprimary_consumer_parent = primaryconsumer.find_parent('ul') print immediateprimary_consumer_parent
登录后复制搜索同级标签
Beautiful Soup 还提供了搜索同级标签的功能。
使用函数
find_next_siblings()
函数能够搜索同一级的下一个所有标签,而find_next_sibling()
函数能够搜索同一级的下一个标签。producers = soup.find(id='producers') next_siblings = producers.find_next_siblings() print next_siblings
登录后复制同样,也可以使用
find_previous_siblings()
和find_previous_sibling()
方法来搜索上一个同级的标签。搜索下一个标签
使用
find_next()
方法将搜索下一个标签中第一个出现的,而find_next_all()
将会返回所有下级的标签项。# 搜索下一级标签 first_p = soup.p all_li_tags = first_p.find_all_next("li") print all_li_tags
登录后复制搜索上一个标签
与搜索下一个标签类似,使用
find_previous()
和find_all_previous()
方法来搜索上一个标签。以上是详解Python利用Beautiful Soup模块搜索内容方法的详细内容。更多信息请关注PHP中文网其他相关文章!
- 标签,返回结果也是返回出现的第一个匹配内容。

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

Python和C 各有优势,选择应基于项目需求。1)Python适合快速开发和数据处理,因其简洁语法和动态类型。2)C 适用于高性能和系统编程,因其静态类型和手动内存管理。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

Python在科学计算中的应用包括数据分析、机器学习、数值模拟和可视化。1.Numpy提供高效的多维数组和数学函数。2.SciPy扩展Numpy功能,提供优化和线性代数工具。3.Pandas用于数据处理和分析。4.Matplotlib用于生成各种图表和可视化结果。

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优
