Open In App

Show text inside the tags using BeautifulSoup

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite:

In this article, we will learn how to get a text from HTML tags using BeautifulSoup. Here we will use requests & BeautifulSoup Module in Python.

The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response.

pip install requests

Beautiful Soup is a Python library designed for quick turnaround projects like screen-scraping.

pip install beautifulsoup4

Method 1: We can use text property. It will only print the text from the tag.

Python3




# Import Required Module
import requests
from bs4 import BeautifulSoup
 
# Web URL
 
# Get URL Content
r = requests.get(Web_url)
 
# Parse HTML Code
soup = BeautifulSoup(r.content, 'html.parser')
 
tag = soup.find("p")
 
print(tag.text)


Output:

Skip to content

Method 2: We can also use get_text() method. This method is used for printing the whole text of the web page

Python3




# Import Required Module
import requests
from bs4 import BeautifulSoup
 
# Web URL
 
# Get URL Content
r = requests.get(Web_url)
 
# Parse HTML Code
soup = BeautifulSoup(r.content, 'html.parser')
 
tag = soup.find("p")
 
print(tag.get_text())


Output:

February 1, 2021

Method 3: If there is only a string inside the tag then we can use the string property.

Python3




# Import Required Module
import requests
from bs4 import BeautifulSoup
 
# Web URL
 
# Get URL Content
r = requests.get(Web_url)
 
# Parse HTML Code
soup = BeautifulSoup(r.content, 'html.parser')
 
tag = soup.find("p")
 
print(tag.string)


Output:

February 1, 2021


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads