Beautiful Soup - previous_siblings 屬性



方法描述

位於相同縮排級別的 HTML 標籤稱為兄弟標籤。Beautiful Soup 中的 previous_siblings 屬性返回一個生成器物件,用於迭代當前標籤之前的所有標籤和字串(在相同的父元素下)。這與 find_previous_siblings() 方法的輸出類似。

語法

element.previous_siblings

返回型別

previous_siblings 屬性返回一個包含兄弟 PageElements 的生成器。

示例 1

下面的示例解析給定的 HTML 字串,該字串在外部 <p> 標籤內嵌套了一些標籤。使用 previous_siblings 屬性獲取 <u> 標籤之前的兄弟標籤。

from bs4 import BeautifulSoup
soup = BeautifulSoup("<p><b>Excellent</b><i>Python</i><u>Tutorial</u></p>", 'html.parser')

tag1 = soup.u
print ("previous siblings:")
for tag in tag1.previous_siblings:
   print (tag)

輸出

previous siblings:
<i>Python</i>
<b>Excellent</b>

示例 2

在以下示例中使用的 index.html 檔案中,HTML 表單中有三個輸入元素。我們找出在 <form> 標籤下,id 設定為 marks 的元素之前的兄弟標籤是什麼。

from bs4 import BeautifulSoup

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

tag = soup.find('input', {'id':'marks'})
sibs = tag.previous_siblings
print ("previous siblings:")
for sib in sibs:
   print (sib)

輸出

previous siblings:

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

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

示例 3

頂級 <html> 標籤總是有兩個兄弟標籤 - head 和 body。因此,<body> 標籤只有一個之前的兄弟標籤,即 head,如下程式碼所示:

html = '''
<html>
   <head>
      <title>Hello</title>
   </head>
   <body>
      <p>Excellent</p><p>Python</p><p>Tutorial</p>
   </body>
   </head>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tags = soup.body.previous_siblings
print ("previous siblings:")
for tag in tags:
   print (tag)

輸出

previous siblings:

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