Extract a YouTube video ID from a given URL using Python (Flask), HTML, and CSS, follow this simple implementation.
Features
Supports various YouTube URL formats.
– `https://www.youtube.com/watch?v=VIDEO_ID`
– `https://youtu.be/VIDEO_ID`
– `https://www.youtube.com/embed/VIDEO_ID`
– `https://www.youtube.com/shorts/VIDEO_ID`
– `https://m.youtube.com/watch?v=VIDEO_ID`
Backend (Python – Flask)
Save this as `app.py`:
```python from flask import Flask, render_template, request import re app = Flask(__name__) def get_youtube_video_id(url): """Extracts the YouTube Video ID from different URL formats.""" regex = r"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/|youtube\.com\/shorts\/)([^\"&?\/\s]{11})" match = re.search(regex, url) return match.group(1) if match else None @app.route("/", methods=["GET", "POST"]) def index(): video_id = None if request.method == "POST": url = request.form.get("youtubeUrl") video_id = get_youtube_video_id(url) return render_template("index.html", video_id=video_id) if __name__ == "__main__": app.run(debug=True)
Frontend (HTML + CSS)
Create a folder named `templates` and inside it, save this file as `index.html`:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>YouTube Video ID Extractor</title> <style> body { font-family: Arial, sans-serif; text-align: center; margin: 50px; background-color: #f4f4f4; } input, button { padding: 10px; margin: 10px; width: 80%; max-width: 400px; border-radius: 5px; border: 1px solid #ccc; } button { background-color: #ff0000; color: white; cursor: pointer; border: none; } button:hover { background-color: #cc0000; } #result { font-weight: bold; color: green; margin-top: 20px; } </style> </head> <body> <h2>YouTube Video ID Extractor Python</h2> <form method="POST"> <input type="text" name="youtubeUrl" placeholder="Enter YouTube URL" required> <button type="submit">Get Video ID</button> </form> {% if video_id %} <p id="result">Video ID: <strong>{{ video_id }}</strong></p> {% endif %} </body> </html>
How to Run the Project?
1. Install Flask if you haven’t:
pip install flask
2. Run the Python script:
python app.py
3. Open your browser and go to:
http://127.0.0.1:5000/
How It Works?
1. User enters a YouTube URL and clicks “Get Video ID”.
2. Flask extracts the video ID using regex and displays it.
3. If the URL is invalid, it shows nothing.
Now you have a Python-powered YouTube Video ID extractor.