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:
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:
pip --version #If pip isn't installed you can always install using this command sudo apt-get install python3-pip - Next, install
pipenv. It works likevirtualenv, but also tracks your dependencies automatically in aPipfile. Install it with:
pip3 install pipenv - Once
pipenvis installed, create a new directory for your project files:
mkdir myproject cd 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.
pipenv shell - With the environment active, install Pytube:
pipenv install pytube - That installs pytube inside your environment. Now create a Python file to hold the script:
touch app.py - Add this code to
app.py:
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:
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.