A Python Script for Downloading YouTube Videos
Tags: automation, script, tutorial, pytube
Published: 2023-03-10 11:26:53

It is no surprise that YouTube has become a great platform where you could find lots of video resources like courses, music videos, movies, etc. For a self-taught programmer like me, it has become a daily go-to resource whenever am stuck on my coding projects. On YouTube, there are a lot of exciting videos and you might want to have some of these videos on your local machine, this means that you will need a video downloader app to download them. What if I tell you that you can build your video downloader using Python? In this article, I will be showing you how you can build a Python script that will download for you YouTube videos from the ground up using a lightweight and simple-to-use library called **[pytube](https://pytube.io/en/latest/)**.

Here is what we will cover:
   - Installing **pytube**
   - Creating the script
   - Testing the script
   - Conclusion 


## Installing pytube
First things first, let’s install the **pytube** library, in your terminal enter this command:
`$ pip install pytube`
Make sure you have an internet connection as you are installing the library.


## Creating the script
After successfully installing the library, create a new Python file and call it **video_downloader_script.py**, you can name it whatever you what as long as the name is meaningful. Do the following imports:
```python
from pytube.cli import on_progress # this displays download progress in the console
from pytube import YouTube
```

Now that the imports are taken care of, let’s create the video download handler, this is the function that will handle the video download task. Below the imports, paste this code:
```python
# this is the handler/function for downloading the video
# the function takes the video url as an argument
def video_downloader(video_url):
    # passing the video url and progress_callback to the YouTube object
    my_video = YouTube(video_url, on_progress_callback=on_progress)
    # downloading the video in high resolution
    my_video.streams.get_highest_resolution().download()
    # return the video title
    return my_video.title
```

To be on the same page, let’s break down the **video_downloader()** function. We, first of all, pass a video URL to the function and inside it, we create a **YouTube** object. This object has a lot of methods like **streams**, **get_highest_resolution**, **download**, etc. **streams** will get all the available streams for the video, **get_highest_resolution** will return the highest resolution for the video and **download** is for downloading the video. And the last line of the function returns the video title.


Below the function add these lines of code:
```python
"""
    Running the code inside the try/except block
"""
try:
    # getting the url from the user
    youtube_link = input('Enter the YouTube link:')
    print(f'Downloading your Video, please wait.......')
    # passing the url to the function
    video = video_downloader(youtube_link)
    # printing the video title
    print(f'"{video}" downloaded successfully!!')

except:
    print(f'Failed to download video')
```
Here is the breakdown of the code snippet, we have a **try/except** block, inside the **try** we are getting the link from the user via the **input()** function. We are then printing a message to the console using the **print()** function, after that, we are making a function call and passing the video link to this function. Finally, we are printing a successful message to the console.

The **except** will run if there are errors while downloading the video. 


## Testing the script
It is now time we test the script, go on YouTube and copy any video link of your choice. Run the script using this command:
`$ python video_downloader_script.py`

You will be prompted to enter the video link, and if you enter the link this is the output:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0gk3naeymq5w7hqr5i9.png)

After the download is complete this is the output you will get:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4drakkcq785hrf5wwqqx.png)

And if you check your current working directory, you will see a video file:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mxsn3k0hkvbe3yl23hsk.png)



Suppose we had no internet connection, the **except** statement will execute and the output would be this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a2qb5ijk0vek9wpze8lc.png)

Something worth mentioning here is not every video that is downloadable on YouTube with this script, some videos require a subscription, some are restricted to a certain region, some are live streams, etc.

## Conclusion
 
That’s it, geeks!!!! I hope you have learned so much from this article. There is so much that you can do with this library, for more information do read its documentation. Thanks for reading.