Beautiful Soup 简明教程
Beautiful Soup - next_elements Property
Method Description
在 Beautiful Soup 库中,next_elements 属性返回包含解析树中的下一个字符串或标签的生成器对象。
In Beautiful Soup library, the next_elements property returns a generator object containing the next strings or tags in the parse tree.
Example 1
next_elements 属性返回出现在文档字符串中 <b> 标签之后的标签和 NavibaleStrings,如下所示:
The next_elements property returns tags and NavibaleStrings appearing after the <b> tag in the document string below −
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)
Example 2
所有出现在 <p> 标签之后的元素列在下面:
All the elements appearing after the <p> tag are listed below −
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 标签旁边的元素列在下面:
The elements next to the input tag present in the HTML form of index.html are listed below −
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)