Beautiful Soup - find_next() 方法



方法描述

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

语法

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

参数

  • name − 标签名称过滤器。

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

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

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

返回值

此 find_next() 方法返回一个 Tag 或 NavigableString。

示例 1

此示例使用了包含以下脚本的网页 index.html。

<html>
   <head>
      <title>TutorialsPoint</title>
   </head>
   <body>
      <h1>TutorialsPoint</h1>
      <form>
         <input type = 'text' id = 'nm' name = 'name'>
         <input type = 'text' id = 'age' name = 'age'>
         <input type = 'text' id = 'marks' name = 'marks'>
      </form>
   </body>
</html>

我们首先找到<form>标签,然后找到它后面的标签。

from bs4 import BeautifulSoup

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

输出

<form>
<input id="nm" name="name" type="text"/>
<input id="age" name="age" type="text"/>
<input id="marks" name="marks" type="text"/>
</form>

示例 2

在此示例中,我们首先找到具有 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_next())

输出

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

示例 3

<head>标签后面的标签恰好是<title>标签。

from bs4 import BeautifulSoup

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

tag = soup.head
print (tag.find_next())

输出

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