一、方法描述
在 BeautifulSoup 库中,find_next()
方法用于查找第一个与给定条件匹配并且在文档中出现在当前元素之后的 PageElement
。此方法返回紧跟在当前标签之后的第一个标签或 NavigableString
。与其他查找方法一样,此方法有如下语法:
二、语法
find_next(name, attrs, string, **kwargs)
三、参数
-
-
-
string
:一个过滤器,用于带有特定文本的 NavigableString
。
-
四、返回值
find_next()
方法返回一个 Tag
或 NavigableString
。
五、示例
示例 1
一个包含以下脚本的网页 index.html
已经被用于本例:
<html>
<head>
<title>Yoagoa</title>
</head>
<body>
<h1>Yoagoa</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>Yoagoa</title>