Python で YouTube から動画をダウンロードする

yt-dlp を使えば可能だった。

import sys
from yt_dlp import YoutubeDL

def download_video(video_url):
  ydl_opts = {
    "format": "best",
  }
  with YoutubeDL(ydl_opts) as ydl:
    ydl.download([video_url])

def download_audio(video_url):
  ydl_opts = {
    "format": "m4a/bestaudio/best",
    "postprocessors": [{
      "key": "FFmpegExtractAudio",
      "preferredcodec": "m4a",
    }]
  }
  with YoutubeDL(ydl_opts) as ydl:
    ydl.download([video_url])

if __name__ == "__main__":
  args = sys.argv
  if 2 <= len(args):
    #download_video(args[1])
    download_audio(args[1])
  else:
    print("Arguments are too short. Ex: python download.py <video_url>")