Beautiful Soup - find_previous_siblings() 方法



方法描述

Beautiful Soup 包中的 find_previous_siblings() 方法返回文档中在此 PAgeElement 之前出现的所有与给定条件匹配的兄弟节点。

语法

find_previous_siblings(name, attrs, string, limit, **kwargs)

参数

  • name − 标签名称过滤器。

  • attrs − 属性值过滤器字典。

  • string − 具有特定文本的 NavigableString 过滤器。

  • limit − 找到这么多结果后停止查找。

  • kwargs − 属性值过滤器字典。

返回值

find_previous_siblings() 方法返回一个包含 PageElements 的 ResultSet。

示例 1

让我们为此目的使用以下 HTML 代码段:

<p>
   <b>
      Excellent
   </b>
   <i>
      Python
   </i>
   <u>
      Tutorial
   </u>
</p>

在下面的代码中,我们尝试查找 <> 标签的所有兄弟节点。在用于抓取的 HTML 字符串中,同一级别还有两个标签。

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

tag1 = soup.find('u')
print ("previous siblings:")
for tag in tag1.find_previous_siblings():
   print (tag)

输出

<i>Python</i>
<b>Excellent</b>

示例 2

网页 (index.html) 包含一个具有三个输入元素的 HTML 表单。我们找到一个 id 属性为 marks 的元素,然后找到其之前的兄弟节点。

from bs4 import BeautifulSoup

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

tag = soup.find('input', {'id':'marks'})
sibs = tag.find_previous_sibling()
print (sibs)

输出

[<input id="age" name="age" type="text"/>, <input id="nm" name="name" type="text"/>]

示例 3

HTML 字符串有两个 <p> 标签。我们找出 id 属性为 id1 的标签之前的兄弟节点。

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')
ptags = tag.find_previous_siblings()
for ptag in ptags:
   print ("Tag: {}, Text: {}".format(ptag.name, ptag.text))

输出

Tag: p, Text: Python
Tag: b, Text: Excellent
广告

© . All rights reserved.