Beautiful Soup - next_elements 属性



方法描述

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

语法

Element.next_elements

返回值

next_elements 属性返回一个生成器。

示例 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)

输出

Next elements:
Excellent

Python

Python <p id="id1">Tutorial</p> Tutorial

示例 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))

输出

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

示例 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)

输出

Next elements:

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

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

© . All rights reserved.