Skip to content

Instantly share code, notes, and snippets.

@leferrad
Last active June 17, 2024 01:55
Show Gist options
  • Save leferrad/67ee653e6af863d08e30ef90f52c8067 to your computer and use it in GitHub Desktop.
Save leferrad/67ee653e6af863d08e30ef90f52c8067 to your computer and use it in GitHub Desktop.
Script to download MP3 files from YouTube links
"""Script to download Audio files from YouTube links.
Pip dependencies:
- pytube
"""
import os
import time
from pytube import Playlist, YouTube
def download(playlist_url, destination_path="/tmp/"):
"""
Download MP3 files from items of a YouTube playlist.
Args:
playlist_url: str, URL to YouTube playlist
destination_path: str, path to folder where the downloaded files will be stored
Examples:
>>> from ytdownloader import download
>>> playlist_url = "..." # fill with playlist url
>>> download(playlist_url,
>>> destination_path="/tmp/")
"""
# Checks on parameters
assert os.path.exists(destination_path), f"Not valid path '{destination_path}' for destination"
# Get videos for playlist
playlist = Playlist(playlist_url)
print(f"Processing playlist '{playlist.title}'")
# Set destination folder (same name as playlist title)
folder = os.path.abspath(os.path.join(destination_path, playlist.title))
if not os.path.exists(folder):
os.mkdir(folder) # Create folder
os.chdir(folder) # Place in folder for downloads
# Start downloading videos
for url in playlist:
try:
print(f"Downloading video from: {url} ...")
YouTube(url).streams.get_audio_only().download()
except Exception as e:
print(f"Exception occurred while processing video '{url}'. "
f"Either the video has no quality as set by you, or it is not available. "
f"Error: {str(e)}")
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment