YouTubeビデオPythonのタイトルを抽出します

Sep 16 2020

YouTubeビデオからオーディオを抽出するために、Pythonで小さなコードを記述しました。コードは次のとおりです。

from __future__ import unicode_literals
import youtube_dl

link = input("Enter the video link:")
name = input("Enter the title of the video:")

path = f'D:\\{name}.mp3'

ydl_opts = {
    'outtmpl':path,
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([link])

ここでやりたかったのは、ユーザーにビデオのタイトルを尋ねるのではなく、リンクを使用してビデオのタイトルを取得することです。私はいくつかの方法を試しましたが、うまくいきませんでした。これを行う簡単な方法はありますか?ありがとう。

回答

1 AlexandraDudkina Sep 16 2020 at 15:44

次のようにextract_infoメソッドを使用できます。

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    info_dict = ydl.extract_info(video, download=False)
    video_title = info_dict.get('title', None)