Download Any YouTube Video With 5 Lines Of Code In Python

Download Any YouTube Video With 5 Lines Of Code In Python

So am going to teach you how to download any YouTube video you like with 5 lines of python. seems impossible right? Don't worry it possible and achieving anything in tech is Possible.

Let Start Coding

There are few steps for us to take in achieving this.

First open your code editor(VScode or Atom)

  • create a file and name it anything you like app.py with py as your extension.
  • Then you need to install pytube by running this code in your terminal.
    pip install pytube
    

Once the installation is done, then we need to import YouTube from pytube.

from pytube import YouTube

Then we need to create and call the path in which the video will be downloaded.

DOWNLOAD_FOLDER = "./"

for me I use the current folder as my DOWNLOAD_FOLDER Path.

Then we need to get the link of the video we want to download from YouTube Site.

video_url = "https://www.youtube.com/watch?v=x7X9w_GIm1s"

The video_url is a YouTube video Python in 100 Seconds

Then we need to create a youtube object and assign the video_url to it.

video_obj = YouTube(video_url)

Then we need to create a media stream and know there are streaming technique adopted by YouTube.

stream = video_obj.streams.get_highest_resolution()

Then we need to use the download method to save the file

stream.download(DOWNLOAD_FOLDER)

Your Code Should Be Like This

from pytube import YouTube
DOWNLOAD_FOLDER = "./"
video_url = "https://www.youtube.com/watch?v=x7X9w_GIm1s"
video_obj = YouTube(video_url)
stream = video_obj.streams.get_highest_resolution()
stream.download(DOWNLOAD_FOLDER)

Then one more thing, you could add a print statement to know when is done, by writing this one line of code.

print("Download Complete")

Then click the Run button on your code editor and watch how your video get downloaded into your folder. Hurray you made it!!!

  • Want to read the pytube doc, here is the link pytube doc

Thanks for reading. follow me on twitter @Eworld_Tech