Beautiful Soup - next_sibling 屬性



方法描述

出現在相同縮排級別的 HTML 標籤稱為兄弟標籤。PageElement 的 next_sibling 屬性返回同一級別或在同一父元素下的下一個標籤。

語法

element.next_sibling

返回型別

next_sibling 屬性返回一個 PageElement、一個 Tag 或一個 NavigableString 物件。

示例 1

index.html 頁面包含一個 HTML 表單,其中包含三個輸入元素,每個元素都有一個 name 屬性。在下面的示例中,查找了 name 屬性為 nm 的輸入標籤的下一個兄弟標籤。

from bs4 import BeautifulSoup

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

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('input', {'id':'nm'})
sib = tag.next_sibling
print (sib)

輸出

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

示例 2

在下一個示例中,我們有一個 HTML 文件,其中包含幾個標籤在 <p> 標籤內。next_sibling 屬性返回其 <b> 標籤旁邊的標籤。

from bs4 import BeautifulSoup 

soup = BeautifulSoup("<p><b>Hello</b><i>Python</i></p>", 'html.parser')

tag1 = soup.b 
print ("next:",tag1.next_sibling)

輸出

next: <i>Python</i>

示例 3

考慮以下文件中的 HTML 字串。它在同一級別有兩個 <p> 標籤。第一個 <p> 的 next_sibling 應該給出第二個 <p> 標籤的內容。

html = '''
<p><b>Hello</b><i>Python</i></p>
<p>TutorialsPoint</p>
'''
soup = BeautifulSoup(html, 'html.parser')

tag1 = soup.p
print ("next:",tag1.next_sibling)

輸出

next:

在 next: 這個詞後面出現空行是意料之外的。但這是因為第一個 <p> 標籤後面有一個 \n 字元。將 print 語句更改如下所示,以獲取 next_sibling 的內容。

tag1 = soup.p
print ("next:",tag1.next_sibling.next_sibling)

輸出

next: <p>TutorialsPoint</p>
廣告

© . All rights reserved.