DEV Community

Cover image for πŸŽ₯ I Built a Professional YouTube Downloader with Python - Here's How!
Dus Mamud
Dus Mamud

Posted on

πŸŽ₯ I Built a Professional YouTube Downloader with Python - Here's How!

πŸŽ₯ I Built a Professional YouTube Downloader with Python

Ever wanted to download YouTube videos or extract audio for offline listening? I created a comprehensive, production-ready YouTube downloader that handles everything from single videos to entire playlists!

🌟 What Makes This Special?

Unlike basic downloaders, this tool is built for real-world use with features you actually need:

  • 🎬 Single Video Downloads - Quick and easy
  • πŸ“ Playlist Support - Download entire playlists with organized structure
  • πŸ“‹ Bulk Downloads - Process multiple URLs from a text file
  • 🎡 Multiple Formats - MP4, MP3, M4A with quality control
  • 🎯 Quality Options - From 144p to 4K for videos, 128k to 320k for audio
  • πŸ–₯️ Cross-Platform - Works on Windows, macOS, and Linux
  • 🎨 Interactive CLI - User-friendly interface with colored output

πŸš€ Quick Start

# Clone the repository
git clone https://github.com/dusmamud/youtube-downloader.git
cd youtube-downloader

# Install dependencies
pip install -r requirements.txt

# Download a video
python youtube_downloader.py "https://www.youtube.com/watch?v=VIDEO_ID"
Enter fullscreen mode Exit fullscreen mode

That's it! You're ready to go.

πŸ’‘ Real-World Usage Examples

Download Audio as MP3

Perfect for music or podcasts:

python youtube_downloader.py "VIDEO_URL" -f audio -o mp3 -q 320k
Enter fullscreen mode Exit fullscreen mode

Download Entire Playlist

Great for educational content:

python youtube_downloader.py "PLAYLIST_URL" -p
Enter fullscreen mode Exit fullscreen mode

Bulk Download from File

Create a urls.txt file:

https://www.youtube.com/watch?v=VIDEO_ID_1
https://www.youtube.com/watch?v=VIDEO_ID_2
https://www.youtube.com/playlist?list=PLAYLIST_ID
Enter fullscreen mode Exit fullscreen mode

Then run:

python youtube_downloader.py -b urls.txt -q 720p
Enter fullscreen mode Exit fullscreen mode

Get Video Info Without Downloading

python youtube_downloader.py "VIDEO_URL" -i
Enter fullscreen mode Exit fullscreen mode

Output:

πŸ“Ή Video Information:
  Title: Amazing Video Title
  Duration: 03:33
  Uploader: Channel Name
  Views: 1.7B
  Upload Date: 20091025
Enter fullscreen mode Exit fullscreen mode

πŸ—οΈ Architecture & Design

Project Structure

youtube-downloader/
β”œβ”€β”€ youtube_downloader.py    # Main CLI interface
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ downloader.py        # Core downloader class
β”‚   └── utils.py             # Utility functions
β”œβ”€β”€ tests/                   # Unit tests
β”œβ”€β”€ docs/                    # Comprehensive documentation
└── requirements.txt         # Dependencies
Enter fullscreen mode Exit fullscreen mode

Key Technologies

yt-dlp: The powerhouse behind the downloads. It's a fork of youtube-dl with better performance and more features.

colorama: Cross-platform colored terminal output for better UX.

FFmpeg: For audio conversion (MP3/M4A).

Core Features Implementation

1. Modular Design

class YouTubeDownloader:
    def __init__(self, output_dir: str = "downloads"):
        self.output_dir = Path(output_dir)
        self.video_qualities = {...}
        self.audio_qualities = {...}

    def download_single(self, url, format_type, quality, output_format):
        # Single video download logic

    def download_playlist(self, playlist_url, ...):
        # Playlist download logic

    def bulk_download(self, urls, ...):
        # Bulk download logic
Enter fullscreen mode Exit fullscreen mode

2. Quality Management

video_qualities = {
    '144p': 'worst[height<=144]',
    '720p': 'best[height<=720]',
    '1080p': 'best[height<=1080]',
    '4K': 'best[height<=2160]',
    'best': 'best'
}

audio_qualities = {
    '128k': 'bestaudio[abr<=128]',
    '320k': 'bestaudio[abr<=320]',
    'best': 'bestaudio/best'
}
Enter fullscreen mode Exit fullscreen mode

3. Error Handling

try:
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    print(f"{Fore.GREEN}βœ“ Successfully downloaded!")
    return True
except Exception as e:
    print(f"{Fore.RED}βœ— Error: {str(e)}")
    return False
Enter fullscreen mode Exit fullscreen mode

🎨 User Experience Design

Interactive Mode

Run without arguments for a guided experience:

python youtube_downloader.py
Enter fullscreen mode Exit fullscreen mode

The tool presents a friendly menu:

🎯 Interactive Mode
Enter YouTube URL (or 'quit' to exit):
URL: https://youtube.com/watch?v=...

πŸ“‹ Select download type:
1. πŸŽ₯ Single video/audio
2. πŸ“ Entire playlist
3. ℹ️  Get video info only
4. πŸ”™ Enter new URL

Choice (1-4):
Enter fullscreen mode Exit fullscreen mode

Colored Output

Using colorama for better visual feedback:

  • 🟒 Green for success
  • πŸ”΄ Red for errors
  • 🟑 Yellow for warnings
  • πŸ”΅ Cyan for information

πŸ“Š Testing & Quality Assurance

Automated Testing

# Run comprehensive test suite
python test_project.py

# Run unit tests
python -m pytest tests/ -v
Enter fullscreen mode Exit fullscreen mode

Test Coverage

  • βœ… Dependencies check
  • βœ… File structure validation
  • βœ… Module imports
  • βœ… Basic functionality
  • βœ… Unit tests (9/9 passed)

Overall Score: 82.6% PASS πŸŽ‰

πŸ”§ Advanced Features

Custom Output Directory

python youtube_downloader.py "VIDEO_URL" -d "~/MyVideos"
Enter fullscreen mode Exit fullscreen mode

Format Conversion

Automatic conversion to MP3 or M4A:

python youtube_downloader.py "VIDEO_URL" -f audio -o mp3
Enter fullscreen mode Exit fullscreen mode

Playlist Organization

Playlists are automatically organized:

downloads/
└── playlist_downloads/
    β”œβ”€β”€ 01 - First Video.mp4
    β”œβ”€β”€ 02 - Second Video.mp4
    └── 03 - Third Video.mp4
Enter fullscreen mode Exit fullscreen mode

πŸ“š Documentation

The project includes comprehensive documentation:

  • Installation Guide - Platform-specific setup instructions
  • Usage Guide - Detailed examples and use cases
  • Troubleshooting Guide - Common issues and solutions
  • Contributing Guide - How to contribute to the project
  • Test Guide - How to test the project

🀝 Contributing

Contributions are welcome! The project follows standard open-source practices:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests
  5. Submit a pull request

🎯 Use Cases

For Students

  • Download educational videos for offline study
  • Save lecture series and tutorials
  • Extract audio from language learning videos

For Content Creators

  • Backup your own content
  • Download reference materials
  • Archive important videos

For Music Lovers

  • Convert music videos to MP3
  • Download entire playlists
  • Create offline music libraries

For Researchers

  • Archive video content for analysis
  • Download documentary series
  • Save interview recordings

βš–οΈ Legal & Ethical Considerations

Important: This tool is for educational and personal use only. Please:

  • Respect YouTube's Terms of Service
  • Honor copyright laws
  • Only download content you have permission to download
  • Support content creators through official channels

πŸš€ Future Enhancements

Planned features for upcoming releases:

  • πŸ“Š Download progress bars with ETA
  • πŸ”„ Resume interrupted downloads
  • πŸ“± Mobile-optimized quality presets
  • πŸŽ›οΈ Advanced filtering options
  • πŸ” Authentication for private videos
  • 🌐 Proxy support
  • πŸ“¦ GUI version
  • πŸ”Œ Plugin system

πŸ“ˆ Performance

The tool is optimized for:

  • Speed: Parallel processing for bulk downloads
  • Reliability: Comprehensive error handling
  • Efficiency: Minimal memory footprint
  • Compatibility: Works with Python 3.7+

πŸŽ“ What I Learned

Building this project taught me:

  1. API Integration: Working with yt-dlp's extensive API
  2. CLI Design: Creating intuitive command-line interfaces
  3. Error Handling: Graceful failure and user feedback
  4. Testing: Writing comprehensive test suites
  5. Documentation: Creating user-friendly docs
  6. Cross-Platform Development: Ensuring compatibility

πŸ”— Links

πŸ’¬ Feedback

I'd love to hear your thoughts! Have you built something similar? What features would you add? Drop a comment below! πŸ‘‡


If you found this useful, please ⭐ star the repository on GitHub and share it with others who might benefit from it!

Happy Downloading! πŸŽ‰

Top comments (4)

Collapse
 
tallship profile image
Bradley D. Thornton

Very nicely formatted and presented article. I've been checking out the actual application, and I had some questions as to why anyone would need something beyond yt-dlp, which I've been using for quite some time now, and I must say, you've done a fine job with this product.

I've also scoured over your Git repo's docs and again, very sensible and comprehensive layout - if most other developers put such effort into their documentation they wouldn't have an endless flow of open issues that consist of users simply asking basic questions.

For most n00bs, the interactive mode is prolly the way they're gonna go... initially, and then they'll start venturing out into more precision, since they're already on the CLI.

The product works as advertised and quickly too, I like snappy. Everyone does. Let's dive into your roadmap though, shall we?

πŸ“Š Download progress bars with ETA

Yup - I'm wondering why it wasn't already implemented, and early on in the project?

πŸ”„ Resume interrupted downloads

This has always been a popular item with any software for some reason, but years of experiencing various forms and levels of success/failure/frustration and wasted time trying (i.e., some FTP servers historically support resume and others don't - no mention of which ones do however), have let me to a point (with the exception of torrents) where the times I try to resume anything that broke is far and few between - again, it's exceedingly rare that I'll try to resume a failed download for any reason. I find it's faster just to start over and get it done.

That's just me though. Some people will try four and five times because they should be able to resume - in the meantime, I've completed my d/l and moved on to the next task at hand.

πŸ“± Mobile-optimized quality presets

WhatEv. people should use Termux or NixOnDroid and just run this from the shell on their Android IMNSHO. Alternatively, you might wanna try your hand at pushing out an app based on this product to F-Droid - I wouldn't even bother with the Google Play Store.

Further, if you do produce an Android App port of your product, I would highly encourage you to do so via your Git repo using a "Custom F-Droid Repo" - that way, people have three choices:

  • They can install from Github
  • They can install from F-Droid, with the F-Droid keys having signed it. They do this on a Best effort basis according to time constraints, but it usually only takes a few days from submission until they can push your product out and the new version becomes available.
  • Anyone specifying your custom F-Droid repo will get all update notifications immediately - the betas or 'rc' versions typically won't be recommended but they'll be there for the adventurous, and the stable releases will be recommended, and automatically d/l'd and installed onto the user's Android device.

FairEmail, my favorite MUA, and IMO way better than K9 Mail, is setup to do automatic updates directly from Github if you install it from there; you're prompted to download the release package APK and when that finishes you have to press to install it. With an F-Droid custom repo or regular F-Droid repo that will/can happen automatically for stable releases. I encourage you to look and see how he does that for his users :)

There's also Obtanium which is quite popular too.

πŸŽ›οΈ Advanced filtering options

As long as you don't complicate what you already have, and leave this for the truly demanding powerusers - again, don't complicate things for the n00bs ;)

πŸ” Authentication for private videos

I used to use a sandboxed freeware youtube downloader on Windows (back when I used to use Wndows), and they actually had this option where you could set up logins and it worked great - until it didn't, and then you got another update and it worked great, until it didn't, Etc.

But you already know that going down that road means that this particular aspect of usage for your product is going to be playing whack-a-mole with YT. The nice thing however, is that this will have no impact on people who aren't actually using it for d/l'ing this particular class of videos anyway - So Go for it.

🌐 Proxy support

This neither means here nor there to me. I use WireGuard in different geographical places for different things, but if you think it's worth the trouble for people who won't take the initiative to set up their own tunnels in the first place, and with respect to Android, you should be aware that things like the DuckDuckGo browser have a localhost loop proxy that may interfere with such things (it can be disabled per app, and generally is for YouTube and a few other things anyway) to thwart trackers.

If you do this, I'd leave it to last - after you build a GUI - anyone working on the CLI already knows how to do these things for themselves, IMO.

πŸ“¦ GUI version

Oh, yeah baby! Did I mention that at first, I didn't see why I should be using what you've produced from yt-dlp until I played with your program? Well, this would have removed that question in the first place - a Good GUI (option) is usually a really good thing, and I urge you to make this your next push here - people will say really good things about you if you do ;)

πŸ”Œ Plugin system

The repo size appears to be about 70k as it is. This is a design choice for you to make, but it may be a lot of work for something that overly complicates the ability for people to use features that might just be better off in core - but you decide.

Summary

I think you've done a very fine job, and I also thought that someone should take the time to spend a little more time than just to leave a one-liner to say so for what you released just two days ago.

I hope to see more from you in the future, and remember how impressed I was (and others will be) for not cutting corners on the documentation, giving it the due attention that it deserves.

Best of luck and I hope that helps!

P.S. If you do go ahead with the GUI I'll be happy to create a SlackBuild and be the package maintainer of your d/l'er for Slackware Linux :)

Collapse
 
mcheremnov profile image
Maksym

Nice article, I would definitely try this out in my spare time! Thanks

Collapse
 
itsmegsg profile image
itsmegsg

Nicely written here as well as in your repo.

Collapse
 
random_ti profile image
Random

Really Helpful article, thanxx for this πŸ‘