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.