🕯️ Magic Note
When you parse HTML with BeautifulSoup, you create a tree of Tag objects. find() navigates this tree and returns the first matching Tag. The .text property (also .get_text()) collects all the text inside a tag, stripping away the HTML. For the title tag, this gives you the page title as a clean string.
- Requires BeautifulSoup and an HTML parser like ‘html.parser’
- find() returns the first matching tag, use find_all() for multiple
- .text returns a string, not a Tag object
- Returns an empty string if the title tag exists but is empty
| HTML | Code | Result |
|---|---|---|
| <title>Home</title> | find(“title”).text | “Home” |
| <title>Python Magic</title> | find(“title”).text | “Python Magic” |
| <title></title> | find(“title”).text | “” |
| No title tag | find(“title”).text | AttributeError |
| soup.title.string (alternative) | soup.title.string | None or string |
Python
# Extracting title from a webpage
from bs4 import BeautifulSoup
html = ‘<html><head><title>Feloriya | Code Coffee Conjure</title></head></html>’
soup = BeautifulSoup(html, ‘html.parser’)
title = soup.find(“title”).text
print(title)
# Output: Feloriya | Code Coffee Conjure
Python
# Safe way to extract title (handles missing tag)
from bs4 import BeautifulSoup
html = ‘<html><body>No title here</body></html>’
soup = BeautifulSoup(html, ‘html.parser’)
title_tag = soup.find(“title”)
title = title_tag.text if title_tag else “No title found”
print(title)
# Output: No title found
Python
# Using soup.title as a shortcut
from bs4 import BeautifulSoup
html = ‘<html><head><title>Magic Spells</title></head></html>’
soup = BeautifulSoup(html, ‘html.parser’)
# soup.title returns the tag or None
print(soup.title)
# Output: <title>Magic Spells</title>
print(soup.title.string)
# Output: Magic Spells
- Calling .text directly on soup.find(“title”) without checking for None, causing AttributeError
- Using soup.title.text when soup.title is None, same error
- Forgetting to parse the HTML with BeautifulSoup before searching for the title
⚡ Whisper
The page hides its name in the head, quiet and patient. Your attention finds it. Python reaches in with soft fingers and pulls the title from the noise. Not loud. Not forceful. Just awakened by your gaze. The name appears. The silence breaks.