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)
廣告