Count the number of paragraph tag using BeautifulSoup
Sometimes, while extracting data from an HTML webpage, do you want to know how many paragraph tags are used in a given HTML document? Don’t worry we will discuss about this in this article.
Step 1: First, import the libraries, BeautifulSoup, and os.
from bs4 import BeautifulSoup as bs import os
Step 2: Now, remove the last segment of the path by entering the name of the Python file in which you are currently working.
base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working’))
Step 3: Then, open the HTML file from which you want to read the value.
html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’))
Step 4: Moreover, parse the HTML file in BeautifulSoup.
Step 5: Next, print a certain line if you want to.
print("Number of paragraph tags:")
Step 6: Finally, calculate and print the number of paragraph tags in the HTML document.
Let us consider the simple HTML webpage, which has numerous paragraph tags.
For finding the number of paragraph tags in the above HTML webpage, implement the following code.
In the below program, we will find the number of paragraph tags on a particular website.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course