Beautiful Soup – find_previous Method


Beautiful Soup – find_previous() Method



”;


Method Description

The find_previous() method in Beautiful Soup look backwards in the document from this PageElement and find the first PageElement that matches the given criteria. It returns the first tag or NavigableString that comes before the current tag in the document. Like all other find methods, this method has the following syntax −

Syntax


find_previous(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

The find_previous() method returns a Tag or NavigableString object.

Example 1

In the example below, we try to find which is the previous object before the <body> tag. It happens to be <title> element.


from bs4 import BeautifulSoup

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

Output


<title>TutorialsPoint</title>

Example 2

There are three input elements in the HTML document used in this example. The following code locates the input element with name attribute = age and looks for its previous element.


from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, ''html.parser'')
tag = soup.find(''input'', {''name'':''age''})
print (tag.find_previous())

Output


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

Example 3

The element before <title> happens to be <head> element.


from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, ''html.parser'')
tag = soup.find(''title'')
print (tag.find_previous())

Output


<head>
<title>TutorialsPoint</title>
</head>

Advertisements

”;

Leave a Reply

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