LoginSignup
20
30

More than 3 years have passed since last update.

PythonでYoutubeの動画をダウンロードするまで(2017/11/30現在)

Last updated at Posted at 2017-11-30

メモ書き程度に書いていくので参考になるのかは不明
(あとMarkdownの書き方よく知らんし調べるのも億劫なのでそのまま)

googleのAPIを導入(動画検索用)

pip install --upgrade google-api-python-client

pytubeを入れる(動画ダウンロード用)

pip install pytube

APIのページのサンプルそのまま使う
https://developers.google.com/youtube/v3/code_samples/python#search_by_keyword

この時GoogleAPIをコード内に書く場所があるのでそこを忘れないこと
(書かないと当然エラー)

動かす際に検索するクエリを指定する.
引数(デフォルト)
--q 検索欄に打ち込むキーワード,ダブルクォーテーションで囲めばスペース区切りの検索もできる

ex. python hoge.py --q "baseball fullgame"

--max-result 検索結果最大数を指定,デフォルトは25件(最大50)

ex. python hoge.py --max-result 50

結果として得られるのはYoutubeで検索した時に出てくるページの中身(リスト)
動画だけじゃなくチャンネルとかも入ってくるので,動画だけがほしいときはいじる必要あり
(ここ https://developers.google.com/youtube/v3/docs/search/list のtype欄にヒントあり)

取ってきたデータリストをpytubeのダウンロードに突っ込む
(書いてあるのは平文でうってあるので適当にリストを入力にして動くように直す必要あり)

from pytube import YouTube
YouTube('http://youtube.com/watch?v=ほげほげ').streams.first().download()

あとは待つだけ(多分)

一応自分のコードも貼り付けておく(ほとんどサンプルままだけど……)

# -*- coding: utf-8 -*-

#!/usr/bin/python

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser


# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
#   https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "API_Keys"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  # Call the search.list method to retrieve results matching the specified
  # query term.
  search_response = youtube.search().list(
    q=options.q,
    part="id,snippet",
    maxResults=options.max_results
  ).execute()

  videos = []

  # Add each result to the appropriate list, and then display the lists of
  # matching videos, channels, and playlists.
  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      videos.append("%s" % (search_result["id"]["videoId"]))

  # print "Videos:\n", "\n".join(videos), "\n"

  return videos


if __name__ == "__main__":
  argparser.add_argument("--q", help="Search term", default="Google")
  argparser.add_argument("--max-results", help="Max results", default=50)
  argparser.add_argument("--type", help="search type", default="video")
  args = argparser.parse_args()

  try:
    search_list =  youtube_search(args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)


from pytube import YouTube

for ID in search_list:
    query = 'https://www.youtube.com/watch?v=' + ID
    yt = YouTube(query)
    yt.streams.filter(subtype='mp4').first().download("./videos")

20
30
1

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
20
30