Youtube downloader with python using PyTube library

Mithu Mithu Nov 27, 2019 · 2 mins read
Youtube downloader with python using PyTube library

Create a Youtube downloader with python using PyTube library

So here's the thing,  I was playing around with python and thought why not create a simple program that can download any song from Youtube just by the song name, artist or the Youtube URL.

I listen to music a lot personally and thought may be you guys will like it too..

Let's get started.

PyTube is a light-weight python library to download YouTube videos/audios. It has a bunch of features built in.

We'll require some more libraries as well for doing various tasks.

  1. Beautiful Soup - for scraping links from Youtube
  2. requests - for making HTTP requests to the Youtube
  3. PyTube - ofcourse for downloading the song/video

Before we create the program, make sure those dependencies are installed on your computer.
just run the command:

pip install bs4 requests pytube

Let's do some programming now...


#import the libraries:
#the webbrowser, and os modules are built-in python 3.x.x and above
import webbrowser
from bs4 import BeautifulSoup
import requests
import urllib.request
from pytube import YouTube
import os

#get song name from user
word_list = [] #for storing the links
print("Song name - artist  OR Youtube URL\n")
songToSearch = input()

#searh YouTube for the video/song
query = urllib.parse.quote(songToSearch)
url = "" + query

#get the response and find all the video id (with class yt-uix-title-link)
#and store them in the word_list[]
response = urllib.request.urlopen(url)
html =
soup = BeautifulSoup(html, 'html.parser')
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
#get the first video link
songURL = ""+word_list[0]

yt = YouTube(songURL)
songToDownload = yt.streams.get_by_itag('140') #stream itag 140 is for mp4 audio

#get title and file size of the song/video
songName = yt.title
fileSize = songToDownload.filesize

#download the file
print("downloading.. ["+ str(fileSize/(1024*0.00000095367432)) +"MB]: "+songName) 
print("Download Complete.")

    #rename the mp4 audio file to mp3
    #works on most of the systems with no conversion
    os.rename(songName+".mp4", songName+".mp3")
    print("Converted Succesfully")
    print("Something went wrong. \nPlease convert the file manually.")


Run the program :


Enter the desired song name and your song will be downloaded in the working directory as a mp3 file.


Footnotes: This program just downloads the audio file. The PyTube library can do much more than that.
Checkout the documentation for more.

Also feel free to checkout the repo at Github:

- Mithu Mondal


Join Newsletter
Get the latest news right in your inbox. We never spam!
Written by Mithu Mondal Profile
Something went wrong. Please check your internet connection.

Connect with Mithu