Learn how to create a URL shortener using Python in a few simple steps.
Introduction
A URL shortener is a tool that takes a long URL and converts it into a shorter version that redirects to the original URL. It is commonly used for making URLs more manageable and SEO friendly, especially for social media or when sharing links.
Objective
The objective of this program is to create a simple URL shortener in Python. This program will take a long URL and generate a shortened version that will redirect users to the original URL when visited. This is a great way to enhance user experience, especially for sharing URLs in a compact format.
Python Code for URL Shortener
import hashlib class URLShortener: def __init__(self): self.url_mapping = {} def shorten_url(self, long_url): """Shortens a URL and returns a short version.""" # Generate a short hash from the original URL short_hash = hashlib.md5(long_url.encode()).hexdigest()[:6] short_url = f"http://short.ly/{short_hash}" self.url_mapping[short_url] = long_url return short_url def expand_url(self, short_url): """Expands the short URL back to the original URL.""" return self.url_mapping.get(short_url, "URL not found") # Usage example if __name__ == "__main__": url_shortener = URLShortener() long_url = input("Enter the URL to shorten: ") short_url = url_shortener.shorten_url(long_url) print(f"Shortened URL: {short_url}") # To expand the URL short_url_to_expand = input("Enter the shortened URL to expand: ") original_url = url_shortener.expand_url(short_url_to_expand) print(f"Original URL: {original_url}")
Explanation of Program Structure
This Python program uses a class-based approach to create a simple URL shortener. Below is a breakdown of the program:
- URLShortener Class: Contains methods for shortening and expanding URLs.
- shorten_url: This method takes a long URL as input, generates a short hash (first 6 characters of an MD5 hash), and returns a shortened URL.
- expand_url: This method accepts a shortened URL and returns the original URL by looking it up in a dictionary.
- Usage: The main program prompts the user for a long URL, shortens it, and then prompts the user to enter a shortened URL to get the original URL back.
How to Run the Program
- Make sure Python is installed on your system. If not, download and install it from python.org.
- Copy the provided Python code into a file with a .py extension, for example,
url_shortener.py
. - Open a terminal or command prompt, navigate to the directory containing the Python file, and run the command:
python url_shortener.py
. - The program will prompt you to enter a long URL. After entering the URL, it will output a shortened URL.
- You can also expand the shortened URL by entering it when prompted.