pythonpytube

I am trying to download the first 10 videos from a YouTube playlist. However, it keeps downloading more than 10


Pretty much the title. This is my code for what I am trying to do.

from pytube import Playlist
from youtube_transcript_api import YouTubeTranscriptApi

link = "https://www.youtube.com/playlist?list=PLI1yx5Z0Lrv77D_g1tvF9u3FVqnrNbCRL"
playlist = Playlist(link)

maxVideos = 10
start = 0

while start < maxVideos:
    for video in playlist.videos:
        start = start + 1
        try:
            print("Attempting to Download Video")
            video.streams.first().download()
            print("Done Downloading")
        except:
            print("Video age restricted.\n Downloading Next Video")

I tried a while loop as you can see over here. I also tried to make a new playlist where it was just the first 10 videos like this:

playlist = Playlist(link)
newPlaylist = playlist.video_urls[:10]

for video in newPlaylist.videos:

But I get an AttributeError saying that 'list' has no attribute 'videos'

I know I can just get the links for first 10 videos from the playlist that download but I want to minimize the number of lines that I have so it can be more efficient.


Solution

  • Try this

    from pytube import Playlist
    from youtube_transcript_api import YouTubeTranscriptApi
    
    link = "https://www.youtube.com/playlist?list=PLI1yx5Z0Lrv77D_g1tvF9u3FVqnrNbCRL"
    playlist = Playlist(link)
    
    maxVideos = 10
    start = 0
    
    for video in playlist.videos:
        start = start + 1
        if(start<=maxVideos):
          try:
              print("Attempting to Download Video")
              video.streams.first().download()
              print("Done Downloading")
          except:
              print("Video age restricted.\n Downloading Next Video")