Beautiful Soup - 解析文档的一部分



假设您想使用 Beautiful Soup 仅查看文档的 <a> 标签。通常,您会解析树并使用 find_all() 方法,并使用所需的标签作为参数。

soup = BeautifulSoup(fp, "html.parser")

tags = soup.find_all('a')

但这将非常耗时,并且会不必要地占用更多内存。相反,您可以创建一个 SoupStrainer 类的对象,并将其用作 BeautifulSoup 构造函数的 parse_only 参数的值。

SoupStrainer 告诉 BeautifulSoup 要提取哪些部分,并且解析树仅包含这些元素。如果您将所需信息缩小到 HTML 的特定部分,这将加快搜索结果的速度。

product = SoupStrainer('div',{'id': 'products_list'})
soup = BeautifulSoup(html,parse_only=product)

以上代码行将仅从产品站点解析标题,这些标题可能位于标签字段内。

类似地,就像上面一样,我们可以使用其他 soupStrainer 对象从 HTML 标签中解析特定信息。以下是一些示例 -

示例

from bs4 import BeautifulSoup, SoupStrainer

#Only "a" tags
only_a_tags = SoupStrainer("a")

#Will parse only the below mentioned "ids".
parse_only = SoupStrainer(id=["first", "third", "my_unique_id"])
soup = BeautifulSoup(my_document, "html.parser", parse_only=parse_only)

#parse only where string length is less than 10
def is_short_string(string):
   return len(string) < 10

only_short_strings = SoupStrainer(string=is_short_string)

SoupStrainer 类采用与来自“搜索树”的典型方法相同的参数:name、attrs、text 和 **kwargs。

请注意,如果您使用 html5lib 解析器,此功能将不起作用,因为在这种情况下将解析整个文档,无论如何。因此,您应该使用内置的 html.parser 或 lxml 解析器。

您还可以将 SoupStrainer 传递到“搜索树”中介绍的任何方法中。

from bs4 import SoupStrainer

a_tags = SoupStrainer("a")
soup = BeautifulSoup(html_doc, 'html.parser')
soup.find_all(a_tags)
广告

© . All rights reserved.