Extract title from a webpage using Python

Extract title from a webpage using Python

To extract the title from a webpage using Python, you can use the BeautifulSoup library along with a library like requests to fetch the webpage content. Here's a step-by-step guide:

1. Install the required libraries:

You'll need beautifulsoup4 and requests:

pip install beautifulsoup4 requests 

2. Extract the title:

Here's a function to fetch and extract the title from a given URL:

import requests from bs4 import BeautifulSoup def extract_title_from_url(url): # Fetch the webpage content response = requests.get(url) response.raise_for_status() # Raise an exception for HTTP errors # Parse the webpage content with BeautifulSoup soup = BeautifulSoup(response.content, 'html.parser') # Extract the title title = soup.title.string if soup.title else None return title # Test url = "https://www.example.com" print(f"Title of {url}: {extract_title_from_url(url)}") 

When you run the script, it fetches the webpage content from the given URL, parses it, and extracts the title using BeautifulSoup. Adjust the url variable to extract titles from different webpages.


More Tags

ssrs-2008 accordion end-of-line spacy mailchimp formbuilder message callstack predict breakpoints

More Programming Guides

Other Guides

More Programming Examples