Beautiful Soup 简明教程

Beautiful Soup - previous_siblings Property

Method Description

在同一缩进级别上出现的 HTML 标签称为同级标签。Beautiful Soup 中的 previous_siblings 属性返回一个生成器对象,用于迭代当前标签之前的同级标签和字符串,它们位于相同父项下。它给出的输出与 find_previous_siblings() 方法类似。

Syntax

element.previous_siblings

Return type

previous_siblings 属性返回同级 PageElements 的一个生成器。

Example 1

以下示例解析给定的 HTML 字符串,其中有一些标签嵌入在外部 <p> 标签中。我们借助 previous_siblings 属性获取了下划线标签的前一个同级标签。

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

tag1 = soup.u
print ("previous siblings:")
for tag in tag1.previous_siblings:
   print (tag)

Output

previous siblings:
<i>Python</i>
<b>Excellent</b>

Example 2

在以下示例使用的 index.html 文件中,HTML 表单中存在三个输入元素。我们找出与 id 标记为 marks 的同级标签中位于 <form> 标签下的同级标签。

from bs4 import BeautifulSoup

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

tag = soup.find('input', {'id':'marks'})
sibs = tag.previous_siblings
print ("previous siblings:")
for sib in sibs:
   print (sib)

Output

previous siblings:

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

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

Example 3

<html> 的顶级标签始终存在两个同级标签——head 和 body。因此,<body> 标签只有一个前一个同级标签,即 head,如下代码所示:

html = '''
<html>
   <head>
      <title>Hello</title>
   </head>
   <body>
      <p>Excellent</p><p>Python</p><p>Tutorial</p>
   </body>
   </head>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tags = soup.body.previous_siblings
print ("previous siblings:")
for tag in tags:
   print (tag)

Output

previous siblings:

<head>
<title>Hello</title>
</head>