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>

附加的行是由于生成器中的换行符导致的。

广告

© . All rights reserved.