FRsmall

Writing a YouTube Download Script in Python

This is not a guide on how to manually write a custom download script, but how to automate youtube-dl library with a simple Python script.

This guide only works on Windows.


		import subprocess

		anotherdownload = ''

		print("""
		                    Welcome to the YouTube Video Downloader.
		             This program will print the highest quality video/audio.

		     """)

		while True:
		    videoURL = input('Enter the full video URL: ')
		    question = input('Are you downloading a playlist? Y/N: ')
		    playlist = ''
		    anotherdownload = ''

		    if question.lower() in ('y', 'yes'):
		        playlist = '--yes-playlist'
		    elif question.lower() in ('n', 'no'):
		        playlist = '--no-playlist'
		    else:
		        print('Sorry I do not understand, downloading single video.')
		        playlist = '--no-playlist'

		    print('Now downloading:', videoURL)

		    subprocess.call(
		        ['youtube-dl', '-f', 'bestvideo+bestaudio',
		         playlist, videoURL, '-o', "\\%(title)s\\"])

		    anotherdownload = input('Would you like to download another video? Y/N: ')

		    if anotherdownload.lower() in ('n', 'no'):
		        print('Thanks for using YouTube Video Downloader.')
		        input('Press any key to exit')
		        break

	

What we will need


We will be using the youtube-dl command line program to download the videos. It is good if you are familiar with the way the commands work, however if you are not you can just use my code which will download the best quality video and audio that it can find.

ffmpeg is required if you want to download anything above 720p, and to properly use this script.

The way my script works is that it looks for the best quality video, and the best quality audio, downloads them separately, and then combines them for one final high-quality file.

Let's get started!

First let's think about what we want our program to do. I want it to download videos at the highest quality, both single videos and playlists. I also want it to keep the original name of the video. I want this to happen easily by just feeding the program a URL, answering a couple of Yes or No questions and then letting it run. I then want the ability to easily download again rather than starting and closing the program each time. We will keep this in mind as we begin to code.

first we will import subprocess module, which we will use to run command line programs in Windows

import subprocess

We will also need an input in order to take the youtube URL. We will worry about catching errors later, we may just be able to let youtube-dl give back an error if an invalid URL is entered and then loop back to the start. So let's just write a simple input.

videoURL = input('Enter the full video URL: ')

We can now get started at looking at our subprocess call. I will let you look at the documentation yourself in order to further customize the command. But essentially what this does is call youtube-dl, then the -f let's us enter the video format code. The bestvideo+bestaudio tells it to download the highest quality that it can and then combine the video/audio files. the videoURL is the input variable that we set. The -o is for the output file name, for which we enter the title of the original video.

subprocess.call(
        ['youtube-dl', '-f', 'bestvideo+bestaudio',
	     videoURL, '-o', "\\%(title)s\\"])

Okay but all this does is allow us to download a video and then it closes. So let's wrap it in a while loop.


	while True:
	    videoURL = input('Enter the full video URL: ')

	    subprocess.call(
	        ['youtube-dl', '-f', 'bestvideo+bestaudio',
	         videoURL, '-o', "\\%(title)s\\"])

We now have an infinite loop so let's ask for another user input to see if they want to exit or download another video. We will take a Y/N answer, but we will be user friendly and take it as .lower() in case they write a typo. We will also accept Yes or No. Since this is a 'while True:' loop we can just look at whether they write no and don't have to take in yes, since if they write yes they just want the loop to continue, which it already does.

So what we are doing is looking at the input in lower-case, then checking if it matches the letter n or no, and breaking the loop. In order to keep our command line open we ask for another input, this is just a trick to keep it open.

We will also need to remember to reset anotherdownload value to an empty string at the start of every loop.


		while True:
			videoURL = input('Enter the full video URL: ')
			anotherdownload = ''

			subprocess.call(
						['youtube-dl', '-f', 'bestvideo+bestaudio',
					 videoURL, '-o', "\\%(title)s\\"])

			anotherdownload = input('Would you like to download another video? Y/N: ')

			if anotherdownload.lower() in ('n', 'no'):
				 print('Thanks for using YouTube Video Downloader.')
				 input('Press any key to exit')
				 break

We want to be able to download playlists. In terms of the subprocess call all we have to add is --yes-playlist if we want to download it, or --no-playlist if we don't. So we will take another input variable and use if else to store it.

We will need to initialize our playlist variable and then we can assign --yes or --no to it. If the user enters anything else we will assume they don't want a playlist.


question = input('Are you downloading a playlist? Y/N: ')
playlist = ''

if question.lower() in ('y', 'yes'):
		playlist = '--yes-playlist'
elif question.lower() in ('n', 'no'):
		playlist = '--no-playlist'
else:
		print('Sorry I do not understand, downloading single video.')
		playlist = '--no-playlist'

We will update our subprocess call to take in the variable playlist


subprocess.call(
		['youtube-dl', '-f', 'bestvideo+bestaudio',
		playlist, videoURL, '-o', "\\%(title)s\\"])

I talked about catching errors earlier. Thankfully if the user enters gibberish youtube-dl spits out an error, and then just repeats the loop. If you want to raise custom errors that is an option but it's not required.

We will add a nice welcoming message and a couple of print statements to let the user know what we are downloading, we then finally end up with:


	import subprocess

	anotherdownload = ''

	print("""
	                    Welcome to the YouTube Video Downloader.
	             This program will print the highest quality video/audio.

	     """)

	while True:
	    videoURL = input('Enter the full video URL: ')
	    question = input('Are you downloading a playlist? Y/N: ')
	    playlist = ''
	    anotherdownload = ''

	    if question.lower() in ('y', 'yes'):
	        playlist = '--yes-playlist'
	    elif question.lower() in ('n', 'no'):
	        playlist = '--no-playlist'
	    else:
	        print('Sorry I do not understand, downloading single video.')
	        playlist = '--no-playlist'

	    print('Now downloading:', videoURL)

	    subprocess.call(
	        ['youtube-dl', '-f', 'bestvideo+bestaudio',
	         playlist, videoURL, '-o', "\\%(title)s\\"])

	    anotherdownload = input('Would you like to download another video? Y/N: ')

	    if anotherdownload.lower() in ('n', 'no'):
	        print('Thanks for using YouTube Video Downloader.')
	        input('Press any key to exit')
	        break

The final result looks like this:



If you want to make it even prettier you can add \n to make new lines and more white space. You can even add more messages. Good luck and let me know if you write any cool scripts.