Mayfair
Mayfair

Reputation: 647

How to display progress of downloading a YouTube video using pytube?

I've been on multiple forums and I've read the docs. I still don't understand how to make this work.

How do I show the progress while the video is being downloaded? Do I need to provide parameters? I see a lot of people doing yt = YouTube(url, on_progress) without parenthesis or parameters so I'm very confused.

I don't know what file_handle should be, I also don't know where I can get the bytes_remaining.

Thank you in advance

def on_progress(stream, chunk, file_handle, bytes_remaining):
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining
    percentage_of_completion = bytes_downloaded / total_size * 100
    print(percentage_of_completion)


def main():
    chunk_size = 1024
    url = "https://www.youtube.com/watch?v=GceNsojnMf0"
    yt = YouTube(url)
    video = yt.streams.get_highest_resolution()
    yt.register_on_progress_callback(on_progress(video, chunk_size, 'D:\\Videos', video.filesize))
    print(f"Fetching \"{video.title}\"..")
    print(f"Fetching successful\n")
    print(f"Information: \n"
          f"File size: {round(video.filesize * 0.000001, 2)} MegaBytes\n"
          f"Highest Resolution: {video.resolution}\n"
          f"Author: {yt.author}")
    print("Views: {:,}\n".format(yt.views))

    print(f"Downloading \"{video.title}\"..")
    video.download('D:\\Videos')

Upvotes: 0

Views: 2554

Answers (1)

Pierre-Loic
Pierre-Loic

Reputation: 1554

The method register_on_progress_callback() from the YouTube object just need a callback function itself not the result of the function. You also need to update the parameters of your function on_progress : only three parameters are used by the method register_on_progress_callback() (stream, chunk and bytes_remaining). You can update your code like that :

def on_progress(stream, chunk, bytes_remaining):
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining
    percentage_of_completion = bytes_downloaded / total_size * 100
    print(percentage_of_completion)


def main():
    chunk_size = 1024
    url = "https://www.youtube.com/watch?v=GceNsojnMf0"
    yt = YouTube(url)
    video = yt.streams.get_highest_resolution()
    yt.register_on_progress_callback(on_progress)
    print(f"Fetching \"{video.title}\"..")
    print(f"Fetching successful\n")
    print(f"Information: \n"
          f"File size: {round(video.filesize * 0.000001, 2)} MegaBytes\n"
          f"Highest Resolution: {video.resolution}\n"
          f"Author: {yt.author}")
    print("Views: {:,}\n".format(yt.views))

    print(f"Downloading \"{video.title}\"..")
    video.download('D:\\Videos')

main()

Upvotes: 1

Related Questions