Beautiful Soup - find_previous() 方法



方法描述

Beautiful Soup 中的 find_previous() 方法從該 PageElement 向文件反向查詢,並查詢與給定條件匹配的第一個 PageElement。它返回文件中當前標籤之前出現的第一個標籤或 NavigableString。與所有其他 find 方法一樣,此方法具有以下語法:

語法

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

引數

  • name − 標籤名稱過濾器。

  • attrs − 屬性值過濾器的字典。

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

  • kwargs − 屬性值過濾器的字典。

返回值

find_previous() 方法返回一個 Tag 或 NavigableString 物件。

示例 1

在下面的示例中,我們嘗試查詢 <body> 標籤之前的上一個物件。它恰好是 <title> 元素。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.body
print (tag.find_previous())

輸出

<title>TutorialsPoint</title>

示例 2

在本示例中使用的 HTML 文件中有三個 input 元素。以下程式碼查詢 name 屬性 = age 的 input 元素,並查詢其上一個元素。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('input', {'name':'age'})
print (tag.find_previous())

輸出

<input id="nm" name="name" type="text"/>

示例 3

<title> 之前的元素恰好是 <head> 元素。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('title')
print (tag.find_previous())

輸出

<head>
<title>TutorialsPoint</title>
</head>
廣告
© . All rights reserved.