Beautiful Soup - next_siblings 屬性



方法描述

在同一縮排級別的 HTML 標籤稱為兄弟標籤。Beautiful Soup 中的 next_siblings 屬性返回一個生成器物件,用於迭代同一父元素下所有後續的標籤和字串。

語法

element.next_siblings

返回型別

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

示例 1

在 index.html 中的 HTML 表單程式碼包含三個輸入元素。以下指令碼使用 next_siblings 屬性來收集具有 id 屬性為 nm 的輸入元素的下一個兄弟元素。

from bs4 import BeautifulSoup

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

輸出

['\n', <input id="age" name="age" type="text"/>, '\n', <input id="marks" name="marks" type="text"/>, '\n']

示例 2

讓我們為此目的使用以下 HTML 程式碼片段:

使用以下程式碼遍歷下一個兄弟標籤。

from bs4 import BeautifulSoup

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

tag1 = soup.b 
print ("next siblings:")
for tag in tag1.next_siblings:
   print (tag)

輸出

next siblings:
<i>Python</i>
<u>Tutorial</u>

示例 3

下一個示例顯示 <head> 標籤只有一個下一個兄弟標籤,即 body 標籤。

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.head.next_siblings
print ("next siblings:")
for tag in tags:
   print (tag)

輸出

next siblings:

<body>
<p>Excellent</p><p>Python</p><p>Tutorial</p>
</body>

附加的行是由於生成器中的換行符導致的。

廣告