A Python YouTube downloader — download videos in any quality or extract audio as MP3, with progress tracking, playlist support, and batch downloading from a text file.
yt-dlp is a maintained fork of youtube-dl that works with 1,000+ sites.
import yt_dlp
# Download best quality video + audio merged
url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'outtmpl': '%(title)s.%(ext)s', # filename = video title
'merge_output_format': 'mp4',
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
print(f"Downloaded: {info['title']}")
Extract just the audio and convert to MP3 using ffmpeg (must be installed).
def download_mp3(url, output_dir='.'):
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality':'192',
}],
'progress_hooks': [progress_hook],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
def progress_hook(d):
if d['status'] == 'downloading':
pct = d.get('_percent_str', '?')
spd = d.get('_speed_str', '?')
eta = d.get('_eta_str', '?')
print(f"\r Downloading: {pct} | Speed: {spd} | ETA: {eta}", end='', flush=True)
elif d['status'] == 'finished':
print(f"\n Conversion to MP3 complete!")
download_mp3('https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'music')
Put one URL per line in urls.txt and download them all.
import sys
def batch_download(urls_file, mode='video', output_dir='downloads'):
import os
os.makedirs(output_dir, exist_ok=True)
with open(urls_file) as f:
urls = [line.strip() for line in f if line.strip() and not line.startswith('#')]
print(f"Downloading {len(urls)} URL(s) in {mode} mode")
for i, url in enumerate(urls, 1):
print(f"\n[{i}/{len(urls)}] {url}")
try:
if mode == 'mp3':
download_mp3(url, output_dir)
else:
ydl_opts = {
'format': 'bestvideo[height<=720]+bestaudio/best[height<=720]',
'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
'merge_output_format': 'mp4',
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
except Exception as e:
print(f" Error: {e}")
print(f"\nAll done! Files saved to '{output_dir}'")
# Example urls.txt:
# https://www.youtube.com/watch?v=xxx
# https://www.youtube.com/watch?v=yyy
batch_download('urls.txt', mode='mp3')
yt-dlp supports 1,000+ websites beyond YouTube — Vimeo, TikTok, Twitter/X, Instagram, and more. Always check copyright and terms of service before downloading — this tool is for personal use and content you have rights to download.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.