Open In App
Related Articles

Show text inside the tags using BeautifulSoup

Improve Article
Improve
Save Article
Save
Like Article
Like

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 15 Mar, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials