python+find_all函数_python爬虫日志(5)find(),find_all()函数

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

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

找到第一辈子产者:html5

生产者在第一个标签里,由于生产者在整个html文档中第一个标签中出现,因此可使用find()方法找到第一辈子产者,在ecologicalpyramid.pypython

中写入下面一段代码,使用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()url

find函数:spa

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

这些参数至关于过滤器同样能够进行筛选处理。不一样的参数过滤能够应用到如下状况:orm

查找标签,基于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()。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值