Skip to content

Instantly share code, notes, and snippets.

@raghavmri
Created December 5, 2021 09:00
Show Gist options
  • Save raghavmri/351ab83a1e8b9817d7f619c5afd83072 to your computer and use it in GitHub Desktop.
Save raghavmri/351ab83a1e8b9817d7f619c5afd83072 to your computer and use it in GitHub Desktop.
youtube_downloader_python
# importing the module
from pytube import YouTube, Playlist
from pathlib import Path
import os
# Global variables
file_size = 0
def main():
print("Welcome to YouTube downloader")
type_of_download = int(
input("Please enter 0 or 1 for single video, playlist respectively: "))
if type_of_download == 0:
url = input("Please enter the url of the video: ")
download_video(url)
elif type_of_download == 1:
play_list_link = input("Please enter the playlist link: ")
playlist = Playlist(play_list_link)
total_no_videos, total_no_of_videos_downloaded = playlist.length, 0
print(f"This playlist has {total_no_videos} videos")
for i in playlist.video_urls:
download_video(i, 2, False)
total_no_of_videos_downloaded += 1
print(
f"Downloaded => {total_no_of_videos_downloaded} of {total_no_videos} videos")
def download_video(url, vid_type=None, showProgress=True):
type_of_vid = None if vid_type == None else int(
input("Please enter 0 or 1 or 2 for downloading only video,only music, both video and music respectively: "))
# Searches for the video and sets up the callback to run the progress indicator.
try:
if showProgress:
video = YouTube(url, on_progress_callback=progress_check)
else:
video = YouTube(url)
except:
print("ERROR. Check your:n -connection -url is a YouTube url and Try again.")
if type_of_vid == 0:
video_type = video.streams.filter(
progressive=True, only_audio=True, file_extension="mp4").get_highest_resolution()
elif type_of_vid == 1:
video_type = video.streams.filter(
only_audio=True, file_extension="mp4").get_highest_resolution()
else:
video_type = video.streams.filter(
file_extension='mp4').get_highest_resolution()
title = video.title
print("Fetching: {}...".format(title))
global file_size
file_size = video_type.filesize
if video_type.exists_at_path(file_path()):
print("File already exists.")
return
video_type.download(file_path())
if showProgress:
print("Download complete!")
# callback function for the progress bar
def progress_check(chunk, file_handle, bytes_remaining):
remaining = (100 * bytes_remaining) / file_size
step = 100 - int(remaining)
print("Completed:", step) # show the percentage of completed download
def file_path(): # Grabs the file path for Downloading the video, Default to the user Music Directory
home = Path.home()
download_path = os.path.join(home, 'Music')
return download_path
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment