【问题标题】:How to add "pytube" downloading info to tqdm Progress Bar?如何将“pytube”下载信息添加到 tqdm 进度条?
【发布时间】:2021-11-14 09:55:01
【问题描述】:

我正在尝试制作 YouTube 视频下载器。 我想在下载 YouTube 视频时制作一个进度条,但我无法获得任何信息(已下载多少 MB 或多少视频 MB)。 我不知道这是否可以通过 python 实现。到目前为止,这是我的代码:

import time , os
from pytube import YouTube
from tqdm import tqdm


al = str(input("C4ommand:"))


if al == "4":
    af = input("Link:")
    you = YouTube(af)

    try:
        os.mkdir("Download")
    except:
        pass

    time.sleep(2)
    time.sleep(1)
    res = you.streams.get_highest_resolution()
    a = res.download()
    with tqdm(total=100) as pbar:
        for i in range(10):
            time.sleep(0.5)
            pbar.update(10)
    print(af + "Link downloading....")
    b = open("\Download", "w")
    b.write(a)
    b.close()
    print("Downloaded")

【问题讨论】:

    标签: python tqdm pytube


    【解决方案1】:

    要查看下载进度,您可以在创建YouTube 实例时使用on_progress_callback 参数。

    pytube quickstart 表示以下内容:

    on_progress_callback 函数将在从视频下载块时运行,并使用三个参数调用:流、数据块和视频中剩余的字节。例如,这可用于显示进度条。

    from pytube import Stream
    from pytube import YouTube
    from tqdm import tqdm
    
    
    def progress_callback(stream: Stream, data_chunk: bytes, bytes_remaining: int) -> None:
        pbar.update(len(data_chunk))
    
    
    url = "http://youtube.com/watch?v=2lAe1cqCOXo"
    yt = YouTube(url, on_progress_callback=progress_callback)
    stream = yt.streams.get_highest_resolution()
    print(f"Downloading video to '{stream.default_filename}'")
    pbar = tqdm(total=stream.filesize, unit="bytes")
    path = stream.download()
    pbar.close()
    print(f"Saved video to {path}")
    

    示例输出:

    Downloading video to 'YouTube Rewind 2019 For the Record  YouTubeRewind.mp4'
    100%|██████████████████████████████| 87993287/87993287 [00:17<00:00, 4976219.51bytes/s]
    Saved video to /tmp/testing/YouTube Rewind 2019 For the Record  YouTubeRewind.mp4
    

    Pytube 有一个内置的进度条,但它不使用tqdm。请参阅https://stackoverflow.com/a/60678355/5666087 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 2020-10-03
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      相关资源
      最近更新 更多