Prerequisite You should have Python installed and the PyTube library available.

Introduction

This guide demonstrates how to set up a Python script to download YouTube videos using the PyTube library. You’ll learn how to install the necessary library, set up your environment, and create a simple script to download videos.

Setup

Step 1: Install Required Package

First, install the necessary package using pip:

pip install pytube

Step 2: Create the Python Script

Create a Python script named download_youtube_video.py with the following content:

from pytube import YouTube

def download_youtube_video(url):
    try:
        # Create a YouTube object
        yt = YouTube(url)

        # Get the highest resolution stream available
        stream = yt.streams.get_highest_resolution()

        # Download the video
        print(f"Downloading '{yt.title}'...")
        stream.download()
        print("Download completed!")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    # Example YouTube URL
    youtube_url = input("Enter the YouTube URL: ")
    download_youtube_video(youtube_url)

Step 3: Run the Script

Execute the script and enter a YouTube URL when prompted:

python download_youtube_video.py

Conclusion

You have successfully set up a Python script to download YouTube videos using PyTube! This guide provided a basic example to get you started. You can now expand on this by customizing the download options and handling different scenarios.