python

Download YouTube videos using Python.

Download a YouTube video from the command line with Python and the pytube library

This post shows how to download YouTube videos with Python, using the pytube library and a virtual environment managed by pipenv.

  • First, make sure Python is installed. If you’re not sure, check with this command:
terminal
python3 --version# This prompt the python3 version that is installed in your system.
  • With Python confirmed, install pip, Python’s package manager, so you can install dependencies:
terminal
pip --version#If pip isn't installed you can always install using this commandsudo apt-get install python3-pip
  • Next, install pipenv. It works like virtualenv, but also tracks your dependencies automatically in a Pipfile. Install it with:
terminal
pip3 install pipenv
  • Once pipenv is installed, create a new directory for your project files:
terminal
mkdir myprojectcd  myproject
  • Run this command to activate the shell. It creates an isolated Python environment, so your project’s dependencies stay separate from the packages installed on your machine.
terminal
pipenv shell
  • With the environment active, install Pytube:
terminal
pipenv install pytube
  • That installs pytube inside your environment. Now create a Python file to hold the script:
terminal
touch app.py
  • Add this code to app.py:
python
from pytube import Youtube as yt
# This will get the youtube video link from the user
video = input('Enter the link of the video you want to download')
# Now we can use that video link to see the available formats of the video
download_video = video.streams.first()
# In this case we will be using the first one but you can view other streams too using streams.all()
download_video.download()
#Withing .download() you can also specify the location where you want to download the video
  • The script is complete. Save it and run it:
terminal
python3 app.py

I also built a fuller video downloader with a friend, using Python and pytube: videodownloader.

Follow me on Twitter for more updates, and feel free to DM if you have questions.