1.一般来说,为了找到BeautifulSoup对象内任何第一个标签入口,使用find()方法。

以上代码是一个生态金字塔的简单展示,为了找到第一生产者,第一消费者或第二消费者,可以使用Beautiful Soup。

找到第一生产者:

生产者在第一个标签里,因为生产者在整个html文档中第一个标签中出现,所以可以使用find()方法找到第一生产者,在ecologicalpyramid.py

中写入下面一段代码,使用ecologicalpyramid.html文件创建BeautifulSoup对象。

from bs4 importBeautifulSoup

with open('ecologicalpyramid.html', 'r') as ecological_pyramid:    #ecological 生态系统 pyramid 金字塔

soup =BeautifulSoup(ecological_pyramid)

producer_entries= soup.find('ul')print(producer_entries.li.div.string)

输出结果:plants

2.find()

find函数:

find(name, attrs, recursive, text, **wargs)    # recursive 递归的,循环的

这些参数相当于过滤器一样可以进行筛选处理。不同的参数过滤可以应用到以下情况:

查找标签,基于name参数

查找文本,基于text参数

基于正则表达式的查找

查找标签的属性,基于attrs参数

基于函数的查找

通过标签查找:

可以传递任何标签的名字来查找到它第一次出现的地方。找到后,find函数返回一个BeautifulSoup的标签对象。

from bs4 importBeautifulSoup

with open('ecologicalpyramid.html', 'r') as ecological_pyramid:

soup= BeautifulSoup(ecological_pyramid, 'html')

producer_entries= soup.find('ul')print(type(producer_entries))

输出结果:

通过文本查找:

直接字符串的话,查找的是标签。如果想要查找文本的话,则需要用到text参数。如下所示:

from bs4 importBeautifulSoup

with open('ecologicalpyramid.html', 'r') as ecological_pyramid:

soup= BeautifulSoup(ecological_pyramid, 'html')

producer_string= soup.find(text = 'plants')print(plants_string)

输出:plants

通过正则表达式查找:

有以下html代码:

想找出第一个邮箱地址,但是第一个邮箱地址没有标签包含,所以通过其他方式很难找到。但是可以将邮箱地址进行正则表达式处理。

importrefrom bs4 importBeautifulSoup

email_id_example= """

The below HTML has the information that has email ids.

abc@example.com

xyz@example.com

foo@example.com"""soup=BeautifulSoup(email_id_example)

emailid_regexp= re.compile("\w+@\w+\.\w+")    # regexp 表达式对象

first_email_id= soup.find(text=emailid_regexp)print(first_email_id)

输出结果:abc@example.com

通过标签属性进行查找:

上面html代码,其中第一个消费者在ul标签里面且id属性为priaryconsumer(priary consumer一次消费者,初级消费者)。

from bs4 importBeautifulSoup

with open('ecologicalpyramid.html', 'r') as ecological_pyramid:

soup= BeautifulSoup(eccological_pyramid, 'html')

primary_consumer= soup.find(id='primaryconsumers')print(primary_consumer.li.div.string)

输出结果:deer

基于定制属性查找:

通过标签属性查找的方式适用大多数标签属性,包括id,style,title,但有 “-”,Class标签属性例外。

比如html5标签中的data-custom属性,如果我们这样

customattr = """

custo attribute

example

"""customsoup= BeautifulSoup(customattr, 'lxml')

customSoup.find(data-custom="custom")

那么则会报错。原因是在python中变量不能含有"-"这个字符,而我们传递的data-custom有这个字符。

解决办法是在attrs属性用字典进行传递参数。

using_attrs = customsoup.find(attrs={'data-custom':'custom'})print(using_attrs)

基于css类的查找:

class是python的保留关键字,所以无法使用class这个关键字。

第一种方法:在attrs属性用字典进行传递参数

css_class = soup.find(attrs={'class':'primaryconsumers'})print(css_class)

第二种方法:BeautifulSoup中的特别关键字参数class_。

css_class = soup.find(class_ = 'primaryconsumers')

基于定义的函数进行查找:

可以传递函数到find()来基于函数定义的条件查找。函数必须返回True或False。

defis_secondary_consumers(tag):return tag.has_attr('id') and tag.get('id') == 'secondaryconsumers'

secondary_consumer =soup.find(is_secondary_consumers)print(secondary_consumer.li.div.string)

输出:fox

将方法进行组合后进行查找:

可以用其中任何方法进行组合进行查找,比如同时基于标签名和id号。

3.find_all查找

find()查找第一个匹配结果出现的地方,find_all()找到所有匹配结果出现的地方。

查找所有3级消费者:

all_tertiaryconsumers = soup.find_all(class_ = 'tertiaryconsumerslist') #tertiary第三的

其中all_tertiaryconsumers的类型是列表。

所以对其列表进行迭代,循环输出三级消费者的名字。

for tertiaryconsumer inall_tertiaryconsumers:print(tertiaryconsumer.div.string)

输出结果:

lion

tiger

find_all()的参数:

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

limit参数可以限制得到的结果的数目。

参照前面的邮件地址例子,得到所有邮件地址:

email_ids = soup.find_all(text=emailid_regexp)print(email_ids)

输出结果:[u'abc@example.com',u'xyz@example.com',u'foo@example.com']

使用limit参数:

email_ids_limited = soup.find_all(text=emailid_regexp, limit = 2)print(email_ids_limited)

限制得到两个结果,所以输出结果:[u'abc@example.com',u'xyz@example.com']

可以向find函数传递True或False参数,如果传递True给find_all(),则返回soup对象的所有标签。对于find()来说,则返回soup对象的第一个标签。

all_texts = soup.find_all(text=True)print(all_texts)

输出结果:

同样,可以在传递text参数时传递一个字符串列表,那么find_all()会找到挨个在列表中定义过的字符串。

all_texts_in_list = soup.find_all(text=['plants', 'algae'])print(all_texts_in_list)

输出结果:

[u'plants', u'alage']

这个同样适用于查找标签,标签属性,定制属性和CSS类。如:

div_li_tags = soup.find_all(['div', 'li'])

并且find()和find_all()都会查找一个对象所有后辈们,不过可以通过recursive参数控制。(recursive回归,递归)

如果recursive=False,只会找到该对象的最近后代。

通过标签之间的关系进行查找

查找父标签

通过find_parents()或find_parent()。它们之间的不同类似于find()和find_all()的区别。

find_parents()返回全部的相匹配的父标签,而find_parent()返回最近一个父标签。适用于find()的方法同样适用于这两个方法。

在第一消费者例子中,可以找到离Primaryconsumer最近的ul父标签。

primaryconsumers = soup.find_all(class_ = 'primaryconsumerlist')

primaryconsumer=primaryconsumers[0]

parent_ul= primaryconsumer.find_parents('ul')print(parent_ul)

一个简单的找到一个标签的父标签的方法是使用find_parent()却不带任何参数。

immediateprimary_consumer_parent = primary_consumer.find_parent()

查找同胞

标签在同一个等级,这些标签是同胞关系,比如参照上面金子塔例子,所有的ul标签就是同胞的关系。上面的ul标签下的producers,primaryconsumers,,

secondaryconsumers,teriaryconsumers就是同胞关系。

div下的plants和algae不是同胞关系,但是plants和临近的number是同胞关系。

Beautiful Soup自带查找同胞的方法。

比如find_next_siblings()和find_next_sibling()查找对象下面的同胞。(sibling兄弟姐妹)

producers = soup.find(id = 'producers')

next_siblings=producers.find_next_siblings()print(next_siblings)

输出结果将会输出与之临近的下面的所有同胞html代码。

查找下一个

对每一个标签来说,下一个元素可能会是定位字符串,标签对象或者其他BeautifulSoup对象,我们定义下一个元素为当前元素最靠近的元素 。

这不用于同胞定义,我们有方法可以找到我们想要标签的下一个其他元素对象。find_all_next()找到与当前元素最靠近的所有对象。而find_next()找到离当前元素最接近的对象。

比如,找到在第一个div标签后的所有li标签

first_div =soup.div

all_li_tags= first_div.find_all_next('li')

查找上一个

与查找下一个相反的是查找前一个,用find_previous()和find_all_previous()。

python bs4 find_all_BeautifulSoup中的find,find_all相关推荐

  1. python soup.find_BeautifulSoup中find和find_all的使用详解

    爬虫利器BeautifulSoup中find和find_all的使用方法 二话不说,先上段HTML例子 index first item second item third item fourth i ...

  2. python bs4标签中含有标签string为空

    用bs4解析的时候发现一个问题,标签中含有标签,string属性打印出来的内容为空. 如: 想要打印出p中的文本内容使用p.string打印结果为None. 查询资料: 获取tag内容有如下三种方法 ...

  3. python - bs4提取XML/HTML中某个标签下的属性

    python - bs4提取XML/HTML中某个标签下的属性 一个例子就让你看明白.看完记得给博主点个赞噢. 我们要提取的xml原始文档来自以下网址: https://raw.githubuserc ...

  4. Python -bs4介绍

    https://cuiqingcai.com/1319.html Python -BS4详细介绍 Python 在处理html方面有很多的优势,一般情况下是要先学习正则表达式的. 在应用过程中有很多模 ...

  5. python提取html中的href标签,如何使用Python从HTML获取href链接?

    原英文标题 How can I get href links from HTML using Python? import urllib2 website = "WEBSITE" ...

  6. python bs4 之 BeautifulSoup 爬虫使用

    python爬虫从入门到放弃(六)之 BeautifulSoup库的使用 上一篇文章的正则,其实对很多人来说用起来是不方便的,加上需要记很多规则,所以用起来不是特别熟练,而这节我们提到的beautif ...

  7. BeautifulSoup中find和find_all的使用

    爬虫利器BeautifulSoup中find和find_all的使用方法 二话不说,先上段HTML例子 <html><head><title>index</t ...

  8. python—bs4模块解析

    一.前言 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你 ...

  9. Python BS4解析库用法详解

    Python BS4解析库用法详解 Beautiful Soup 简称 BS4(其中 4 表示版本号)是一个 Python 第三方库,它可以从 HTML 或 XML 文档中快速地提取指定的数据.Bea ...

最新文章

  1. hdu 4739 状压DP
  2. 《Head First Python》第四章--持久存储
  3. Prototype原型模式(创建型模式)
  4. MySQL binlog和redo/undo的概念
  5. 【转】汇总:LDA理论、变形、优化、应用、工具库
  6. FineUILearning
  7. C程序设计语言现代方法12:指针和数组
  8. 软件开发demo是什么意思_地府后台管理系统demo出来了!附地址
  9. 中国双频前端模块市场趋势报告、技术动态创新及市场预测
  10. Web Service初探
  11. python数学符号读法大全_高等数学中所有符号的读法
  12. 小程序UI与传统HTML5区别
  13. win10专业版激活后变成教育版怎么改回专业版
  14. 选择startup公司的一点经验
  15. 十进制与二进制相互转换(c++)
  16. 微信小程序—带qq表情的评论输入框
  17. Win7系统安装详细教程步骤
  18. 企业微信获取临时素材,此处接口为语音接口
  19. DevOps在证券互联网研发中的应用与实践
  20. pandas分组聚合

热门文章

  1. 下载、安装、配置 java jdk1.8
  2. 小程序用thinkPHP上传文件到腾讯云对象存储空间
  3. 多线程join(加入)
  4. Struts2的动态Action实现
  5. 记一次lnmp经历 nginx 多个php版本支持配置
  6. hi3516a的文件系统错误
  7. mrp软件Java模拟器下载_mrp模拟器
  8. 奔图打印机显示未连接_手机连接奔图打印机,无法打印的解决方法
  9. 浙江大学计算机研究生分数线初试单科学科,2016年浙江大学计算机考研复试分数线_浙江大学考研分数线...
  10. html的编辑器有几种,各种系统下HTML用哪种编辑器