Cool things to do with Python – Youtube Downloads

Fun and cool things to do with python. Learn how download youtube videos.

Card image cap

In this article let me walk you through one of cool things to do with python. This should be useful for beginners to intermediate learners. The focus is giving some inspiration of fun and interesting things to do with python. I will show you how you can download a video or the audio of a video from youtube, and build a simple website using flask to trigger the download.

Python Project | Automate Youtube with Python Tutorial https://img.youtube.com/vi/Y7o0y5MvyKY/default.jpg Python Project | Automate Youtube with Python Tutorial 2020-07-21 https://youtu.be/Y7o0y5MvyKY

What do you need to install?

Here is what you need to complete this python project. You need python and pip installed in your computer. Plus I will use three python modules:

  • pafy: Module that make really easy to access youtube video information and download video
  • youtube_dl: The pafy module uses this module to download the video.
  • certifi: This module includes SSL certificates so youtube can verify the connection and confirm is trustworthy.
  • flask and flask_bootstrap: Module that will help us create the website from where you can trigger the download.

To install these modules run the following commands in your terminal:

pip install pafy
pip install youtube_dl
pip install certifi
pip install flask
pip install flask_bootstrap

Perfect! You are all set up. Let’s see how you can download a video/audio from youtube.

Download video or audio from youtube

The following code will access the youtube video you indicated in the url. Then select the stream to download, audio or video stream, and download it. Yep, the pafy module make this extremely simple! This is the key key piece of code in this python project

import pafy
# Download an audio
video = pafy.new(<REPLACE WITH VIDEO URL>)
audio_stream = video.getbestaudio(preftype='m4a')
audio_stream.download()
import pafy
# Download a video
video = pafy.new(<REPLACE WITH VIDEO URL>)
video_stream = video.getbestvideo()
video_stream.download()

In case you encounter any SSL certificate error, double check the certifi module is installed. You can check running the following command in your terminal

pip list

Create simple flask website

Let’s create a simple website with flask so you can trigger a download from the browser instead of from the terminal. We will need to create two things:

  • An html file containing a form where you will enter the url that will be sent to the web server.
  • A python script that will start our web server. This web server will serve two types of request: Requests to return the html, which the browser will rendered. And also requests to download a given youtube video

Create the html file

First I will create a simple html file containing a header, a form where I will enter the the youtube url and click download. Note this file should be inside the a folder named “templates” so flask can find it.

<!-- Filename: index.html -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
{% extends 'bootstrap/base.html' %} #Use bootstrap styling

{% block content %} <!-- jinja2 tag -->

<header>
    <div class="jumbotron text-center">
        <h1>Youtube Downloads</h1>
    </div>
</header>
<div class="container" class="panel panel-default">
    <form action="/download" method="post">
        <div class="form-row">
            <input type="text" class="form-control"
                   placeholder="Enter a youtube video url"
                   name="firstvideo"
            /> 
<!-- the video url will be inside a variable named firstvideo -->
        </div>
        <div class="form-row">
            <input type="submit" value="Start Downloading" class="btn-info btn-lg" />
        </div>
    </form>

</div>


{% endblock %}

When someone click the “Star Downloading” button, a post request containg /download in the url will send to our web server, as I indicated in the form:

<form action="/download" method="post">

Create the web server

We need a program that handles the requests arriving from the browser, in other words, we need a web server to make this application work. This web server should do two thing:

  • Sending the html we just wrote so the browser render our website
  • Receive download requests.
#Filename: webserver.py
from flask import Flask,render_template, request
from flask_bootstrap import Bootstrap
from download import download_audio

app=Flask(__name__)
Bootstrap(app)

# Return html
@app.route("/")
def index():
    return render_template('index.html')

# Receive download requests
@app.route("/download", methods=['POST'])
def download():
    video1_url = request.form['firstvideo']
    download_audio(video1_url)

    return render_template('index.html')


if __name__=='__main__':
    app.run(port=5000,debug=True)

This web server will listen for requests in port 5000. Let’s see if our application works. To do so, go to your browser and enter the following in the address bar:

http://localhost:5000

If everything went well, you should see the following:

Hope you enjoy the article and discover one of the cool things to do with python. Thank you so much reading my blog. Keep learning!! Don’t give up

In case you would like to learn more about flask, I will highly recommend this book. It includes code examples, nice explanations and it covers all you need to know: jinja, configure mysql, validate user input and more

What next?

Learn to organise your code better with Object Oriented Programming

Make sure your code works using unit testing

If you like the article and you would like to be notified when I publish more articles feel free to follow, give it a like or subscribe. 🙂

Thanks!!

Learn Ethical Hacking From Scratch Course

Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java