Skip to content
Related Articles

Related Articles

Improve Article
BeautifulSoup – Search by text inside a tag
  • Last Updated : 15 Mar, 2021

Prerequisites: Beautifulsoup

Beautifulsoup is a powerful python module used for web scraping. This article discusses how a specific text can be searched inside a given tag.

Approach

  • Import module
  • Pass the URL
  • Request page
  • Specify the tag to be searched
  • For Search by text inside tag we need to check condition to with help of string function.
  • The string function will return the text inside a tag.
  • When we will navigate tag then we will check the condition with the text.
  • Return text

We will see search text inside a tag by two method.

Method 1: iterative 

This method uses for loop for to search for the text.

Example



Python3




from bs4 import BeautifulSoup
import requests
  
# sample web page
  
# call get method to request that page
page = requests.get(sample_web_page)
  
# with the help of beautifulSoup and html parser create soup
soup = BeautifulSoup(page.content, "html.parser")
  
child_soup = soup.find_all('strong')
  
text = 'page table base register (PTBR)'
  
# we will search the tag with in which text is same as given text
for i in child_soup:
    if(i.string == text):
        print(i)

Output

<strong>page table base register (PTBR)</strong>

Method 2: Using lambda

It is a one liner alternative of the above example.

Example

Python3




from bs4 import BeautifulSoup
import requests
  
# sample web page
  
# call get method to request that page
page = requests.get(sample_web_page)
  
# with the help of beautifulSoup and html parser create soup
soup = BeautifulSoup(page.content, "html.parser")
  
text = 'CS Theory Course'
  
# Search by text with the help of lambda function
gfg = soup.find_all(lambda tag: tag.name == "strong" and text in tag.text)
  
print(gfg)

Output

[<strong>CS Theory Course</strong>]

 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




My Personal Notes arrow_drop_up
Recommended Articles
Page :