Downloading YouTube Videos and converting to MP3

A simple guide to download videos from YouTube using python

  1. Objectives:
      1. Download YouTube Videos
      2. Saving as subclip (saving a portion of the video)
      3. Converting to MP3
  2. Required Tools:
      1. PyTube— primarily for downloading youtube videos.
      2. MoviePy — for video editing and also convert to mp3.
  3. Steps:
    1. pip install pytube and moviepy

Basic Usage

from pytube import YouTube
from moviepy.editor import *

# download a file from youtube
youtube_link = ''
w = YouTube(youtube_link).streams.first()"/your/target/directory")

# download a file with only audio, to save space
# if the final goal is to convert to mp3
youtube_link = ''
y = YouTube(youtube_link)
t = y.streams.filter(only_audio=True).all()

Downloading videos from a YouTube playlist

import requests
import re
from bs4 import BeautifulSoup

website = ''
r= requests.get(website)
soup = BeautifulSoup(r.text)

tgt_list = [a['href'] for a in soup.find_all('a', href=True)]
tgt_list = [n for n in tgt_list if'watch',n)]

unique_list= []
for n in tgt_list:
    if n not in unique_list:

# all the videos link in a playlist
unique_list = ['' + n for n in unique_list]

for link in unique_list:
    y = YouTube(link)
    t = y.streams.all()

Converting from MP4 to MP3 (from a folder with mp4 files)

import moviepy.editor as mp
import re
tgt_folder = "/folder/contains/your/mp4"

for file in [n for n in os.listdir(tgt_folder) if'mp4',n)]:
full_path = os.path.join(tgt_folder, file)
output_path = os.path.join(tgt_folder, os.path.splitext(file)[0] + '.mp3')
clip = mp.AudioFileClip(full_path).subclip(10,) # disable if do not want any clipping

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s