Beautiful Soup 简明教程

Beautiful Soup - find_next() Method

Method Description

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

The find_next() method in Beautiful soup finds the first PageElement that matches the given criteria and appears later in the document. returns the first tag or NavigableString that comes after the current tag in the document. Like all other find methods, this method has the following syntax −

Syntax

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

Parameters

  1. name − A filter on tag name.

  2. attrs − A dictionary of filters on attribute values.

  3. string − A filter for a NavigableString with specific text.

  4. kwargs − A dictionary of filters on attribute values.

Return Value

此 find_next() 方法返回一个标签或一个 NavigableString

This find_next () method returns a Tag or a NavigableString

Example 1

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

A web page index.html with following script has been used for this example

<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> 标签,然后再找到其旁边的标签。

We first locate the <form> tag and then the one next to it.

from bs4 import BeautifulSoup

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

Output

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

Example 2

在这个示例中,我们首先找到 name='age' 的 <input> 标签,然后获取其下一个标签。

In this example, we first locate the <input> tag with its name='age' and obtain its next tag.

from bs4 import BeautifulSoup

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

tag = soup.find('input', {'name':'age'})
print (tag.find_next())

Output

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

Example 3

<head> 标签旁边的标签碰巧是 <title> 标签。

The tag next to the <head> tag happens to be <title> tag.

from bs4 import BeautifulSoup

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

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

Output

<title>TutorialsPoint</title>