Beautiful Soup - previous_elements 属性



方法描述

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

语法

Element.previous_elements

返回值

previous_elements 属性返回一个生成器。

示例 1

previous_elements 属性返回文档字符串中<p>标签之前出现的标签和 NavigableStrings −

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('p', id='id1')

pres = tag.previous_elements
print ("Previous elements:")
for pre in pres:
   print (pre)

输出

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

示例 2

下面列出了<u>标签之前出现的所有元素−

from bs4 import BeautifulSoup

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

tag1 = soup.find('u')
print ("previous elements:")
print (list(tag1.previous_elements))

输出

previous elements:
['\n', '\n', 'Python', <i>Python</i>, 'Excellent', <b>Excellent</b>, '\n', <p>
<b>Excellent</b><i>Python</i>
</p>, '\n']

示例 3

BeautifulSoup 对象本身没有任何之前的元素−

from bs4 import BeautifulSoup

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

tag = soup.find('input', id='marks')
pres = soup.previous_elements
print ("Previous elements:")
for pre in pres:
   print (pre.name)

输出

Previous elements:
广告
© . All rights reserved.