Search code examples
pythonyoutubeextractscreen-scrapingyoutube-dl

Extract the title of a YouTube video Python


I have written a small piece of code in python to extract the audio from a YouTube video. Here is the code:

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])

What I wanted to do here is to get the title of the video by using the link instead of asking the user for the title of the video. I tried out few methods, but they didn't work out for me. Is there an easy way to do this? Thanks.


Solution

  • You can use extract_info method in folowing way:

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