Beautiful Soup - find_all_previous() 方法



方法描述

Beautiful Soup 中的 find_all_previous() 方法會從當前 PageElement 向文件的前面查詢,並找到所有符合給定條件且出現在當前元素之前的 PageElement。它返回一個包含在文件中出現在當前標籤之前的 PageElement 的 ResultSet。與所有其他 find 方法一樣,此方法具有以下語法:

語法

find_previous(name, attrs, string, limit, **kwargs)

引數

  • name - 標籤名稱過濾器。

  • attrs - 屬性值過濾器字典。

  • string - 具有特定文字的 NavigableString 過濾器。

  • limit - 找到指定數量的結果後停止查詢。

  • kwargs - 屬性值過濾器字典。

返回值

find_all_previous() 方法返回一個包含 Tag 或 NavigableString 物件的 ResultSet。如果 limit 引數為 1,則該方法等效於 find_previous() 方法。

示例 1

在此示例中,顯示了出現在第一個 input 標籤之前的每個物件的 name 屬性。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('input')
for t in tag.find_all_previous():
   print (t.name)

輸出

form
h1
body
title
head
html

示例 2

在正在考慮的 HTML 文件 (index.html) 中,有三個 input 元素。使用以下程式碼,我們列印 <input> 標籤(nm 屬性為 marks)之前所有前導標籤的標籤名稱。為了區分它之前的兩個 input 標籤,我們還列印了 attrs 屬性。請注意,其他標籤沒有任何屬性。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('input', {'name':'marks'})
pretags = tag.find_all_previous()
for pretag in pretags:
   print (pretag.name, pretag.attrs)

輸出

input {'type': 'text', 'id': 'age', 'name': 'age'}
input {'type': 'text', 'id': 'nm', 'name': 'name'}
form {}
h1 {}
body {}
title {}
head {}
html {}

示例 3

BeautifulSoup 物件儲存整個文件的樹。它沒有任何前導元素,如下例所示:

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tags = soup.find_all_previous()
print (tags)

輸出

[]
廣告