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>
廣告