LoginSignup
4
14

More than 3 years have passed since last update.

【Python】Youtubeの新着動画を自動的にダウンロードしておくコード(違法性なし)

Last updated at Posted at 2021-04-14

はじめに

特定のキーワードに合致する新着動画をYoutubeから検索して自動的にダウンロードしておくプログラムを書きました。
コピペで動かせるので新人プログラマさんにもおすすめです。

本記事で紹介するライブラリは違法性はないとのことですが、youtubeのダウンロードは自己責任でお願いいたします。
※当然「複製して配布」はNGです!

準備

必要なPythonモジュールをインストールします。

pip install google-api-python-client
pip install apiclient
pip install youtube_dl

コード

from __future__ import unicode_literals
import youtube_dl
import apiclient

KEY_WORD = "YOASOBI"          # ダウンロード対象のキーワードを入力
DOWN_DIR = "\\Videos\\"       # ダウンロードフォルダ
API_KEY  = "<APIキーを入力>"   # APIキー

youtube = apiclient.discovery.build("youtube", "v3", developerKey=API_KEY)

def youtube_search():
    search_response = youtube.search().list(
      q=KEY_WORD,
      part="id,snippet",
      maxResults=50,
      order="date"
    ).execute()

    ydl_opts = {"outtmpl": DOWN_DIR + "%(title)s-%(id)s.%(ext)s"}
    for search_result in search_response.get("items", []):
        if search_result["id"]["kind"] == "youtube#video":
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    ydl.download(["https://www.youtube.com/watch?v=%s" % (search_result["id"]["videoId"])])

if __name__ == "__main__":
    youtube_search()

実行結果

無事新着動画がダウンロード出来ています。
1.png

※実行中に撮ったキャプチャです。

このPythonプログラムをタスクスケジューラーやcronで(5分間隔等で)定期実行すれば新着動画を自動的にダウンロードするツールの完成です。

YouTube Data API の使用にはAPIキーが必要です。
下記の記事で取得の説明をしています。

再生回数が1000件以上のものといった絞り込みをしたい場合は以下の記事を参考にしてください。

以上です。

4
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
14