Playlist Downloader Project (code) in Python

← Back to Projects

Playlist Downloader in Python.

About the project: This is a project for a Playlist Downloader in Python. This will be a self-contained script that uses the pytube library to download videos or entire playlists from YouTube.

    Before You Run the Code
  • Install pytube: You'll need to install the pytube library. Open your terminal or command prompt and run the following command:
    
         pip install pytube
         
  • Paste the URL: When you run the script, it will prompt you for the URL of the YouTube playlist you want to download. You can find this URL in your web browser's address bar when you're on the playlist page.

This script will download each video in the playlist to the same directory as the script.

This script provides a complete and interactive Playlist Downloader. When you run it, it will create a new folder with the same name as the playlist's title and save all the downloaded videos inside it.


Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)





# playlist_downloader.py

import os
from pytube import Playlist
from pytube.exceptions import PytubeError

def download_playlist():
    """
    Prompts the user for a YouTube playlist URL and downloads all videos.
    """
    print("--- YouTube Playlist Downloader ---")
    
    # Get the playlist URL from the user
    playlist_url = input("Enter the YouTube playlist URL: ").strip()

    if not playlist_url:
        print("Error: Playlist URL cannot be empty.")
        return

    try:
        # Create a Playlist object
        playlist = Playlist(playlist_url)

        # Get the playlist title and create a folder for downloads
        playlist_title = playlist.title
        # Sanitize the title to be a valid directory name
        sanitized_title = "".join(c for c in playlist_title if c.isalnum() or c in (' ', '_')).rstrip()
        download_folder = os.path.join(os.getcwd(), sanitized_title)

        # Create the download directory if it doesn't exist
        if not os.path.exists(download_folder):
            os.makedirs(download_folder)
            print(f"Created directory: {download_folder}")
        else:
            print(f"Directory already exists: {download_folder}")
        
        print(f"\nFound playlist: '{playlist_title}' with {len(playlist.video_urls)} videos.")
        
        # Loop through each video in the playlist
        for i, video_url in enumerate(playlist.video_urls):
            print(f"\nDownloading video {i + 1}/{len(playlist.video_urls)}...")
            print(f"URL: {video_url}")
            
            try:
                # Get the video object
                video = playlist.videos[i]
                
                # Get the highest resolution stream available
                stream = video.streams.get_highest_resolution()
                
                # Download the video to the specified folder
                stream.download(output_path=download_folder)
                
                print(f"Successfully downloaded: {stream.default_filename}")
            except PytubeError as e:
                print(f"Error downloading video from {video_url}: {e}")
            except Exception as e:
                print(f"An unexpected error occurred: {e}")

        print("\nAll available videos in the playlist have been processed.")

    except PytubeError as e:
        print(f"Error with the provided playlist URL: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def main():
    """
    Main function to run the playlist downloader script.
    """
    download_playlist()

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()




← Back to Projects