LoginSignup
80
83

More than 5 years have passed since last update.

PythonでYouTubeの動画を自動的に検索&ダウンロードする

Last updated at Posted at 2014-01-29

使用するライブラリ

gdata

Python client library for Google data APIs

GoogleのAPI。YouTubeの動画を検索したりできる

pytube

Github: ablanco/python-youtube-download

YouTubeの動画をダウンロードする

YouTubeの動画を検索する

gdataを使ってYouTubeから動画を検索してみましょう

# -*- coding: utf-8 -*-
# 日本語で検索したい場合は上のタグを入れる

from gdata import *
import gdata.youtube
import gdata.youtube.service

search_word = "犬" # 犬の動画を検索
client = gdata.youtube.service.YouTubeService()

# サーチクエリを作成
query = gdata.youtube.service,YouTubeVideoQuery()
query.vq = search_word # 検索ワード
query.start_index = 1 # 何番目の動画から検索するか
query.max_results = 10 # いくつの動画情報を取得したいか
query.racy = "exclude" # 最後の動画を含めるか
query.orderby = "relevance" # どんな並び順にするか

# 検索を実行し、feedに結果を入れる
feed = client.YouTubeQuery(query)

for entry in feed.entry:
    # 動画のリンクを取り出す
    # LinkFinderは、
    #   from gdata import *
    # から使用
    link = LinkFinder.GetHtmlLink(entry)
    print link

実行結果

<?xml version='1.0' encoding='UTF-8'?>
<ns0:link xmlns:ns0="http://www.w3.org/2005/Atom" href="https://www.youtube.com/watch?v=ZhCBEbsjdPo&amp;feature=youtube_gdata" rel="alternate" type="text/html" />
.
.
.

こんな感じで10個のリンクを取得出来ました。
次にこのリンクを参考にして動画をダウンロードするのですが、必要なのは"href"の部分だけなので、切り出してあげましょう。

# 先ほど取得したリンクデータの1つ
url = '<ns0:link xmlns:ns0="http://www.w3.org/2005/Atom" href="https://www.youtube.com/watch?v=wwAHyzfEEKc&amp;feature=youtube_gdata" rel="alternate" type="text/html" />'

print url.split('href="')[1].split('&')[0]
# 結果 >>> 'https://www.youtube.com/watch?v=wwAHyzfEEKc'

注意:
もしforループなどで一気に検索したい場合は、max_resultsは最大50まで、ループの回数は10回までになります。つまり、一度に検索できる最大動画数は500になります。

YouTubeの動画をダウンロードする

from pytube import YouTube

yt = YouTube()
yt.url = 'https://www.youtube.com/watch?v=wwAHyzfEEKc'

# ダウンロードを実行
video = yt.get('mp4')
video.download('/path/to/videos/download/folder') # 好きなフォルダにダウンロードしてくれる

実行結果

Downloads-2.png

こんなかんじで簡単にダウンロード出来ました。
今回紹介したプログラムを組み合わせると、一度に最大500まで動画をダウンロードできます。

80
83
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
80
83