Beautiful Soup – find Method


Beautiful Soup – find() Method



”;


Method Description

The find() method in Beautiful Soup looks for the first Element that matches the given criteria in the children of this PageElement and returns it.

Syntax


Soup.find(name, attrs, recursive, string, **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

The find() method returns Tag object or a NavigableString object

Example 1

Let us use the following HTML script (as index.html) for the purpose


<html>
   <head>
      <title>TutorialsPoint</title>
   </head>
   <body>
      <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>

The following Python code finds the element with its id as nm


from bs4 import BeautifulSoup

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

obj = soup.find(id = ''nm'')
print (obj)

Output


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

Example 2

The find() method returns the first tag in the parsed document that has the given attributes.


obj = soup.find(attrs={"name":''marks''})

Output


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

Example 3

If find() can”t find anything, it returns None


obj = soup.find(''dummy'')
print (obj)

Output


None

Advertisements

”;

Leave a Reply

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