Beautiful Soup – find_all_next Method


Beautiful Soup – find_all_next() Method



”;


Method Description

The find_all_next() method in Beautiful Soup finds all PageElements that match the given criteria and appear after this element in the document. This method returns tags or NavigableString objects and method takes in the exact same parameters as find_all().

Syntax


find_all_next(name, attrs, string, limit, **kwargs)

Parameters

  • name − A filter on tag name.

  • attrs − A dictionary of filters on attribute values.

  • recursive − If this is True, find() a recursive search will be performed. Otherwise, only the direct children will be considered.

  • limit − Stop looking after specified number of occurrences have been found.

  • kwargs − A dictionary of filters on attribute values.

Return Value

This method returns a ResultSet containing PageElements (Tags or NavigableString objects).

Example 1

Using the index.html as the HTML document for this example, we first locate the <form> tag and collect all the elements after it with find_all_next() method.


from bs4 import BeautifulSoup

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

tag = soup.form
tags = tag.find_all_next()
print (tags)

Output


[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>, <input id="marks" name="marks" type="text"/>]

Example 2

Here, we apply a filter to the find_all_next() method to collect all the tags subsequent to <form>, with id being nm or age.


from bs4 import BeautifulSoup

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

tag = soup.form
tags = tag.find_all_next(id=[''nm'', ''age''])
print (tags)

Output


[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>]

Example 3

If we check the tags following the body tag, it includes a <h1> tag as well as <form> tag, that includes three input elements.


from bs4 import BeautifulSoup

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

tag = soup.body
tags = tag.find_all_next()
print (tags)

Output


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

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *