Beautiful Soup - find 与 find_all 方法



Beautiful Soup 库包含 find() 和 find_all() 方法。这两种方法是解析 HTML 或 XML 文档时最常用的方法之一。您经常需要从特定的文档树中找到具有特定标签类型、特定属性或特定 CSS 样式等的 PageElement。这些条件作为参数传递给 find() 和 find_all() 方法。两者之间的主要区别在于,find() 定位满足条件的第一个子元素,而 find_all() 方法搜索满足条件的所有子元素。

find() 方法的语法如下:

语法

find(name, attrs, recursive, string, **kwargs)

name 参数指定对标签名称的过滤。使用 attrs,可以设置对标签属性值的过滤。如果 recursive 参数为 True,则强制进行递归搜索。您可以将变量 kwargs 作为属性值过滤器的字典传递。

soup.find(id = 'nm')
soup.find(attrs={"name":'marks'})

find_all() 方法采用与 find() 方法相同的所有参数,此外还有一个 limit 参数。它是一个整数,将搜索限制为给定过滤条件的指定出现次数。如果没有设置,find_all() 将在所述 PageElement 下的所有子元素中搜索条件。

soup.find_all('input')
lst=soup.find_all('li', limit =2)

如果 find_all() 方法的 limit 参数设置为 1,则它实际上充当 find() 方法。

两种方法的返回类型不同。find() 方法返回首先找到的 Tag 对象或 NavigableString 对象。find_all() 方法返回一个 ResultSet,其中包含满足过滤条件的所有 PageElement。

以下示例演示了 find 和 find_all 方法的区别。

示例

from bs4 import BeautifulSoup

markup =open("index.html")

soup = BeautifulSoup(markup, 'html.parser')
ret1 = soup.find('input')
ret2 = soup.find_all ('input')
print (ret1, 'Return type of find:', type(ret1))
print (ret2)
print ('Return tyoe find_all:', type(ret2))

#set limit =1
ret3 = soup.find_all ('input', limit=1)
print ('find:', ret1)
print ('find_all:', ret3)

输出

<input id="nm" name="name" type="text"/> Return type of find: <class 'bs4.element.Tag'>
[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>, <input id="marks" name="marks" type="text"/>]
Return tyoe find_all: <class 'bs4.element.ResultSet'>
find: <input id="nm" name="name" type="text"/>
find_all: [<input id="nm" name="name" type="text"/>]
广告
© . All rights reserved.