Trích xuất tiêu đề của video YouTube Python

Sep 16 2020

Tôi đã viết một đoạn mã nhỏ bằng python để trích xuất âm thanh từ video YouTube. Đây là mã:

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

Điều tôi muốn làm ở đây là lấy tiêu đề của video bằng cách sử dụng liên kết thay vì hỏi người dùng về tiêu đề của video. Tôi đã thử một số phương pháp, nhưng chúng không hiệu quả với tôi. Có cách nào làm dễ hơn không? Cảm ơn.

Trả lời

1 AlexandraDudkina Sep 16 2020 at 15:44

Bạn có thể sử dụng phương thức extract_info theo cách sau:

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