Last modified: Jan 10, 2023 By Alexander Williams

BeautifulSoup: Find Form Tag

Find Form Tag using find()

from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module

# 👇 HTML Source
hrml_source = '''
<div>
    <form action="/go" method="post">
    <input type="text" name="fname">
    <input type="text" name="lname">
    </form>
</div>
'''

soup = BeautifulSoup(hrml_source, 'html.parser') # 👉️ Parsing

form = soup.find("form") # 👉️ Find Form tag

print(form) # 👉️ Print Result

Output:

<form action="/go" method="post">
<input name="fname" type="text"/>
<input name="lname" type="text"/>
</form>

 

print(form['action']) # 👉️ Get Form Action Value

Output:

/go

 

print(form['method']) # 👉️ Get Form Method Value

 Output:

post

 

inputs = form.find_all("input") # 👉️ Find all Inputs tag
print(inputs) # 👉️ Print Result

Output:

[<input name="fname" type="text"/>, <input name="lname" type="text"/>]

 

for input in inputs:
    print(input) # 👉️ Print Input Tag
    print("Name:", input['name']) # 👉️ Input Attribute Name
    print("Type:", input['type']) # 👉️ Input Attribute Type
    print("*" * 5)

Output:

<input name="fname" type="text"/>
Name: fname
Type: text
*****
<input name="lname" type="text"/>
Name: lname
Type: text

Find Form Tag using select_one()

from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module

# 👇 HTML Source
hrml_source = '''
<div>
    <form action="/go" method="post">
    <input type="text" name="fname">
    <input type="text" name="lname">
    </form>
</div>
'''

soup = BeautifulSoup(hrml_source, 'html.parser') # 👉️ Parsing

form = soup.select_one("form") # 👉️ Find Form tag Using select_one()

print(form) # 👉️ Print Result

Output:

<form action="/go" method="post">
<input name="fname" type="text"/>
<input name="lname" type="text"/>
</form>