7

I'm tryng to get some informations from a list of playlists in youtube with youtube-dl. I've written this code but what it takes is not the video's informations but the playlist informations (e.g. the playlist title instead of the video title in the playlist). I can't understand why.

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

Any help will be appreciated.

Lara M.
  • 855
  • 2
  • 10
  • 23
  • First of all, `video` in your code refers to the entire playlist, not any individual videos. – xjcl May 25 '17 at 16:02

2 Answers2

13

The variable you call video actually holds the playlist information, not the video information. You can find a list of the individual video information in the playlist's entries attribute.

See below for a possible fix. I renamed your video variable to playlist and took the freedom to rewrite it a bit and add output:

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)
            )
xjcl
  • 12,848
  • 6
  • 67
  • 89
  • Thanks! I don't understand what `for video in playlist_dict['entries']: print()` does. What does it prints? – Lara M. May 30 '17 at 09:08
  • It just prints an empty line to make it easier to tell the individual videos apart. It doesn't look that pretty if the description is long tho. – xjcl May 30 '17 at 23:18
  • how to save it to text file? – TipVisor Mar 25 '20 at 07:23
  • @TipVisor There's many ways to save it in a text file, just google for "Redirect stdout Python" =) – xjcl Mar 27 '20 at 05:15
5

run the command

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

you can also uses the --get for retriving specific items for example

youtube-dl --get-title https://www.youtube.com/playlist?list=<playlist_id> > example.txt
Alen Paul Varghese
  • 1,278
  • 14
  • 27