In this blog, we will create a simple program with the beautifulsoup library to print title tag. This program makes use of the urlopen function from the urllib library.
urlopen function is used to read html and other files.
We will start our program by importing the urlopen function from the urllib library.
from urllib.request import urlopen
Next, we will import the Beautiful Soup library into our program.
from bs4 import BeautifulSoup
We will be searching for a title tag from page “https://docs.python.org/3/tutorial/index.html” , but before that we need to create a beautifulsoup object.
bs = BeautifulSoup(html.read(),'html.parser')
The above statement is the creation of a beautiful object. It takes two arguments to create a beautiful object. First is the html.read and the second is the parser.
Finally, display the title tag with the print statement.
print(bs.title)
Output
<title>The Python Tutorial — Python 3.10.6 documentation</title>
Complete Code
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://docs.python.org/3/tutorial/index.html")
bs = BeautifulSoup(html.read(),'html.parser')
print(bs.title)