Beautiful Soup - Functions Reference

Beautiful Soup Useful Resources

Beautiful Soup - find_next() Method



Method Description

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

  • name − A filter on tag name.

  • attrs − A dictionary of filters on attribute values.

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

  • kwargs − A dictionary of filters on attribute values.

Return Value

This find_next () method returns a Tag or a NavigableString

Example - Finding next element to Form Tag

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

from bs4 import BeautifulSoup 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> """ soup = BeautifulSoup(html, '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 - Finding Next element of Input with filter

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

from bs4 import BeautifulSoup

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>
"""

soup = BeautifulSoup(html, 'html.parser')

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

Output

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

Example - Finding Tag next ot Head Tag

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

from bs4 import BeautifulSoup

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>
"""

soup = BeautifulSoup(html, 'html.parser')

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

Output

<title>TutorialsPoint</title>
Advertisements