Beautiful Soup 简明教程

Beautiful Soup - next_elements Property

Method Description

在 Beautiful Soup 库中,next_elements 属性返回包含解析树中的下一个字符串或标签的生成器对象。

Syntax

Element.next_elements

Return value

next_elements 属性返回一个生成器。

Example 1

next_elements 属性返回出现在文档字符串中 <b> 标签之后的标签和 NavibaleStrings,如下所示:

html = '''
<p><b>Excellent</b><p>Python</p><p id='id1'>Tutorial</p></p>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
tag = soup.find('b')

nexts = tag.next_elements
print ("Next elements:")
for next in nexts:
   print (next)

Output

Next elements:
Excellent
Python
Python
<p id="id1">Tutorial</p>
Tutorial

Example 2

所有出现在 <p> 标签之后的元素列在下面:

from bs4 import BeautifulSoup

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

tag1 = soup.find('p')
print ("Next elements:")
print (list(tag1.next_elements))

Output

Next elements:
['\n', <b>Excellent</b>, 'Excellent', <i>Python</i>, 'Python', '\n', '\n', <u>Tutorial</u>, 'Tutorial', '\n']

Example 3

出现在 index.html 的 HTML 表单中的 input 标签旁边的元素列在下面:

from bs4 import BeautifulSoup

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

tag = soup.find('input')
nexts = soup.previous_elements
print ("Next elements:")
for next in nexts:
   print (next)

Output

Next elements:

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

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