Beautiful Soup 简明教程
Beautiful Soup - previous_elements Property
Method Description
在 Beautiful Soup 库中,previous_elements 属性返回一个生成器对象,其中包含解析树中的前一个字符串或标签。
In Beautiful Soup library, the previous_elements property returns a generator object containing the previous strings or tags in the parse tree.
Example 1
previous_elements 属性返回在下文档字符串中出现在 <p> 标签前的标记和 NavibaleStrings:
The previous_elements property returns tags and NavibaleStrings appearing before the <p> 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('p', id='id1')
pres = tag.previous_elements
print ("Previous elements:")
for pre in pres:
print (pre)
Output
Previous elements:
Python
<p>Python</p>
Excellent
<b>Excellent</b>
<p><b>Excellent</b><p>Python</p><p id="id1">Tutorial</p></p>
Example 2
出现在 <u> 标签之前的所有元素如下:
All the elements appearing before the <u> 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('u')
print ("previous elements:")
print (list(tag1.previous_elements))
Output
previous elements:
['\n', '\n', 'Python', <i>Python</i>, 'Excellent', <b>Excellent</b>, '\n', <p>
<b>Excellent</b><i>Python</i>
</p>, '\n']
Example 3
BeautifulSoup 对象本身没有任何前一个元素:
The BeautifulSoup object itself doesn’t have any previous elements −
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)