pythonpytube

pytube taking weird amount of time


So when I run Pytube inside the script, it takes 30 seconds to finish, but when I run it in a function, it only takes 0.96 seconds to finish. Why is that? Can someone explain it in simple terms because I am new to Python?

here it took only 0.96 seconbds to finish "inside a function"

here it took 30s to finish in a normal line

and do the function really get all the videos? cuz i print the random index and its give me a small number like 60 from 3000 videos here is the script


import pytube
import time
StarterTick = time.time()
print(StarterTick,type(StarterTick))
VideoList = "list=PLKB9puQeauyBTnMmRWsB4VVfbbWR0tKCc"
PlayList = f"https://www.youtube.com/playlist?{VideoList}"

def getRandomVideo():
    PlayListVideos = pytube.contrib.playlist.Playlist(PlayList,)
    randomIndex = random.randint(0,len(PlayList) -1) # -1 cuz list start with 0 so if we have 5 items it would be 4 but len would return 5 
    print(f"your random index is {randomIndex}")
    return PlayListVideos[randomIndex] # just return a random video from youtube list


# this way it takes 30 s to finish PlayListVideos = pytube.contrib.playlist.Playlist(PlayList)

print(f"here is your random Video {getRandomVideo()}")
print("programm finished")
print(f"THe programm took {time.time() - StarterTick:>3.2f} seconds to finish")

Solution

  • If you ask it to give you the complete playlist by calling something like len(playlist.video_urls) or by iterating through every video URL, it quietly crawls through every page on YouTube and fires off dozens or even hundreds of HTTP requests. On a 3000‑video playlist that easily takes half a minute. In your fast snippet, however, you accidentally used len(PlayList) (the length of the URL string itself), so your random index was always under a hundred and Pytube only ever fetched the first page of the playlist (about 100 videos), which is why it finished in under a second.

    If you really want to pick uniformly from all 3000 videos, you will have to call len(playlist.video_urls), accept that initial crawl delay, and then keep that Playlist object around so you won’t repeat the 30‑second wait. But if you just need a quick hit and don’t mind biasing toward early entries, you can index straight into playlist[i] without asking for the full length, and Pytube will stop fetching as soon as it reaches the page containing your index.