In this article, we are going to see how to find an HTML tag that contains certain text using BeautifulSoup.
Open( filename, mode ): It opens the given filename in that mode which we have passed.
find_all ( ): It finds all the pattern in the file which will match with the passed expression.
Here, in the given below code, we are finding a certain text mentioned as a pattern in the program, in various different tags. Now the code will provide all these tags which will have the text matched with the pattern.
Here we first import the regular expressions and BeautifulSoup libraries. Then we open the HTML file using the open function which we want to parse. Then using the find_all function, we find a particular tag that we pass inside that function and also the text we want to have within the tag. If the passed tag has that certain text, then it is added to a list.
So all the tags having certain text are stored in a list and then the list is printed. If we get the empty list, then it means that there is no such tag having the text we were trying to check.
Below is the HTML file for demonstration:
Below is the implementation:
[<a href=”https://www.geeksforgeeks.org/”>Geeks For Geeks</a>, <a href=”Dummy Check Text”>Geeks For Geeks</a>]
[<span class=”true”>Geeks For Geeks</span>, <span class=”false”>Geeks For Geeks</span>]
[<li class=”1″>Python Program</li>]
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