③BeautifulSoup中的find()函数和findAll()函数

来源:互联网 发布:韩国女演员排行知乎 编辑:程序博客网 时间:2024/05/18 22:45
BeautifulSoup里的find()和findAll()可能是我们最常用的两个函数。使用这两个函数,我们可以通过标签的不同属性轻松地过滤HTML页面,查找需要的标签组或单个标签。其语法格式为: findAll(tag,attributes,recursive,text,limit,keywords) find(tag,attributes,recursive,text,keywords)可以看出,find()函数与findAll()函数的格式只存在一个参数的区别,下面我们以findAll()函数进行讲解,而find()函数用法与之类似。此外,95%的情况下我们只会用到tag和attributes两个参数。<1>标签参数tag:可以传一个标签的名称或多个标签名称组成的Python字典做标签参数tag。
print(soup.findAll(“html”))
<2>属性参数attributes:可以传一个用Python字典封装起来的某个标签的若干个属性及与其对应的属性值做属性参数attributes。
print(soup.findAll(“”,{”class” : {“story”,”sister”}}))
<3>递归参数recursive:一个布尔变量。如果recursive设置为True,findAll就会根据我们的要求去查找标签参数的所有子标签,以及子标签的子标签。如果recursive设置为False,findAll就会只查找文档的一级标签。findAll默认支持递归查找(recursive默认值是True)。一般情况下,这个参数不需要设置。<4>文本参数text:用标签的文本内容去匹配,而不是用标签的属性去匹配。
print(soup.findAll(“”,text = “I am sorry”))
<5>范围限制参数limit:此参数限制返回结果的数量,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果。如果我们只对网页获取的前x项感兴趣,就可以设置limit参数。此外,find等价于findAll的limit=1时的情形。<6>关键词参数keyword:可以选择某些具有特定属性的标签。
print(soup.findAll(“”,id = “link1”))
下面用一代代码详细介绍这些参数的使用以及函数的功能。
from bs4 import BeautifulSouphtml_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p>"""soup = BeautifulSoup(html_doc)#输出soup对象中所有标签名为"title"的标签print(soup.findAll("title"))#输出soup对象中所有标签名为"title"和"a"的标签print(soup.findAll({"title","a"}))#输出soup对象中所有属性为"class"属性值为“sister”的标签print(soup.findAll("",{"class" : "sister"}))#输出soup对象中所有属性为"id"属性值为“link1”的标签print(soup.findAll("",{"id":"link1"}))#输出soup对象中所有属性为“class”属性值为“story”或“title”或“sister”的标签print(soup.findAll("",{"class":{"story","title","sister"}}))#输出soup对象中包含“The Dormouse's story”内容的标签数量(通过文本参数text)print(len(soup.findAll("",text = "The Dormouse's story")))#输出soup对象中所有属性为"id"属性值为“link1”的标签(通过关键字参数keyword)print(soup.findAll("",id = "link1"))#输出soup对象中所有属性为"class"属性值为“sister”的标签(通过关键字参数keyword)print(soup.findAll("",class_ = "sister"))
0 0