Beautiful Soup - find_previous() 方法



方法描述

Beautiful Soup 中的 find_previous() 方法从该 PageElement 向文档反向查找,并查找与给定条件匹配的第一个 PageElement。它返回文档中当前标签之前出现的第一个标签或 NavigableString。与所有其他 find 方法一样,此方法具有以下语法:

语法

find_previous(name, attrs, string, **kwargs)

参数

  • name − 标签名称过滤器。

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

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

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

返回值

find_previous() 方法返回一个 Tag 或 NavigableString 对象。

示例 1

在下面的示例中,我们尝试查找 <body> 标签之前的上一个对象。它恰好是 <title> 元素。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.body
print (tag.find_previous())

输出

<title>TutorialsPoint</title>

示例 2

在本示例中使用的 HTML 文档中有三个 input 元素。以下代码查找 name 属性 = age 的 input 元素,并查找其上一个元素。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('input', {'name':'age'})
print (tag.find_previous())

输出

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

示例 3

<title> 之前的元素恰好是 <head> 元素。

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('title')
print (tag.find_previous())

输出

<head>
<title>TutorialsPoint</title>
</head>
广告
© . All rights reserved.