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.