In this blog post, I will walk you through the process of creating a simple YouTube video downloader script in Python. This script will allow you to download YouTube videos by providing their URLs.
We will use the PyTube library to make this task easy. If you don’t have PyTube installed, the script will attempt to install it for you.
Import Necessary Modules
import importlib
import subprocess
from pytube import YouTube
We start by importing the required modules. importlib
is used to check if the PyTube library is already installed, and subprocess
is used to install PyTube if it’s missing. We also import the YouTube
class from the PyTube library to interact with YouTube videos.
Check if PyTube is Installed
try:
importlib.import_module('pytube')
pytube_installed = True
except ImportError:
pytube_installed = False
We check if the PyTube library is installed on your system. If it is, we set the pytube_installed
flag to True
, indicating that you can proceed with video downloads. If not, the flag is set to False
.
Install PyTube (if not installed)
if not pytube_installed:
try:
subprocess.check_call(['pip', 'install', 'pytube'])
print("PyTube has been installed.")
except subprocess.CalledProcessError:
print("Failed to install PyTube. You can install it manually using 'pip install pytube'.")
else:
print("PyTube is already installed.")
If PyTube is not installed, the script attempts to install it using the pip
command. If the installation is successful, it informs you that PyTube has been installed. Otherwise, it advises you to manually install it.
Get the YouTube Video URL
video_url = input("Enter the YouTube video URL: ")
The script prompts you to enter the URL of the YouTube video you want to download. This URL is then stored in the video_url
variable.
Download the Video
try:
yt = YouTube(video_url)
video_stream = yt.streams.get_highest_resolution()
download_path = './'
video_stream.download(output_path=download_path)
print("Video downloaded successfully to the current directory.")
except Exception as e:
print("An error occurred:", str(e))
Here’s where the magic happens. The script creates a YouTube
object using the provided URL. It selects the highest resolution stream for both video and audio using yt.streams.get_highest_resolution()
. The downloaded video will be saved in the current directory (you can change the download_path
if needed).
If the video is downloaded successfully, it prints a success message. However, if any errors occur during the process, it catches them and displays an error message.
The summarised code can be found below.
import importlib
import subprocess
from pytube import YouTube
# Check if pytube is installed
try:
importlib.import_module('pytube')
pytube_installed = True
except ImportError:
pytube_installed = False
if not pytube_installed:
# pytube is not installed, attempt to install it
try:
subprocess.check_call(['pip', 'install', 'pytube'])
print("pytube has been installed.")
except subprocess.CalledProcessError:
print("Failed to install pytube. You can install it manually using 'pip install pytube'.")
else:
print("pytube is already installed.")
# Ask the user for the YouTube video URL
video_url = input("Enter the YouTube video URL: ")
print("Downloading Started\nProcess in progress......")
try:
# Create a YouTube object
yt = YouTube(video_url)
# Get the highest resolution stream (video + audio)
video_stream = yt.streams.get_highest_resolution()
# Download the video in the current directory
download_path = './'
# Download the video
video_stream.download(output_path=download_path)
print("Video downloaded successfully to the current directory.")
except Exception as e:
print("An error occurred:", str(e))
Conclusion
With this Python script, you can easily download YouTube videos by providing their URLs. It first checks if the PyTube library is installed and attempts to install it if necessary. Then, it asks for the video URL, downloads the video, and informs you of the outcome.
Thanks for reading, and see you in the next post with more automation projects in python.
If you’re as passionate about Cyber-Security as I am, feel free to follow me on Twitter – @ANShrivastava03 for the latest updates and connect with me on LinkedIn – Aditya Narayan to stay in the loop with my posts and insights in the world of digital forensics. Let’s continue this fascinating journey together!