使用 youtube-dl 从播放列表列表中获取视频信息

Get video information from a list of playlist with youtube-dl

我正在尝试使用 youtube-dl 从 YouTube 的播放列表列表中获取一些信息。我已经编写了这段代码,但它需要的不是视频信息而是播放列表信息(例如播放列表标题而不是播放列表中的视频标题)。我不明白为什么。

input_file = open("url")
for video in input_file:
    print(video)
ydl_opts = {
    'ignoreerrors': True
}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl: 
                info_dict = ydl.extract_info(video, download=False)
                for i in info_dict:
                    video_thumbnail = info_dict.get("thumbnail"),
                    video_id = info_dict.get("id"),
                    video_title = info_dict.get("title"),
                    video_description = info_dict.get("description"),
                    video_duration = info_dict.get("duration")

任何帮助将不胜感激。

您调用的变量video实际上保存的是播放列表信息,而不是视频信息。您可以在播放列表的 entries 属性中找到单个视频信息的列表。

请参阅下文了解可能的修复方法。我将你的 video 变量重命名为 playlist 并自由地重写它并添加输出:

import textwrap
import youtube_dl

playlists = [
    "https://www.youtube.com/playlist?list=PLRQGRBgN_EnrPrgmMGvrouKn7VlGGCx8m"
]

for playlist in playlists:

    with youtube_dl.YoutubeDL({"ignoreerrors": True, "quiet": True}) as ydl:
        playlist_dict = ydl.extract_info(playlist, download=False)

    # Pretty-printing the video information (optional)
    for video in playlist_dict["entries"]:
        print("\n" + "*" * 60 + "\n")

        if not video:
            print("ERROR: Unable to get info. Continuing...")
            continue

        for prop in ["thumbnail", "id", "title", "description", "duration"]:
            print(prop + "\n" +
                textwrap.indent(str(video.get(prop)), "    | ", lambda _: True)
            )

运行命令

youtube-dl --print-json https://www.youtube.com/playlist?list=<playlist_id> > example.json

您还可以使用 --get 来检索特定项目,例如

youtube-dl --get-title https://www.youtube.com/playlist?list=<playlist_id> > example.txt