如何添加进度条?

13

有没有办法在pytube中添加进度条?我不知道如何使用以下的方法:

pytube.Stream().on_progress(chunk, file_handler, bytes_remaining)

我的代码:

from pytube import YouTube
# from pytube import Stream
from general import append_to_file


def downloader(video_link, down_dir=None):
    try:
        tube = YouTube(video_link)
        title = tube.title
        print("Now downloading,  " + str(title))
        video = tube.streams.filter(progressive=True, file_extension='mp4').first()
        print('FileSize : ' + str(round(video.filesize/(1024*1024))) + 'MB')
        # print(tube.streams.filter(progressive=True, file_extension='mp4').first())
        # Stream(video).on_progress()
        if down_dir is not None:
            video.download(down_dir)
        else:
            video.download()
        print("Download complete, " + str(title))
        caption = tube.captions.get_by_language_code('en')
        if caption is not None:
            subtitle = caption.generate_srt_captions()
            open(title + '.srt', 'w').write(subtitle)
    except Exception as e:
        print("ErrorDownloadVideo  |  " + str(video_link))
        append_to_file('debug', format(e))
    # FILESIZE print(tube.streams.filter(progressive=True, file_extension='mp4').first().filesize/(1024*1024))
9个回答

15

您也可以这样做,而无需编写自己的函数。

代码:

from pytube import YouTube
from pytube.cli import on_progress #this module contains the built in progress bar. 
link=input('enter url:')
yt=YouTube(link,on_progress_callback=on_progress)
videos=yt.streams.first()
videos.download()
print("(:")

这只能在命令提示符中运行吗? 我尝试在Pycharm中使用它,但根本不起作用。 - Toma

7
在Youtube类内调用您的进度函数。 yt = YouTube(video_link, on_progress_callback=progress_function) 以下是您的进度函数。
def progress_function(self,stream, chunk,file_handle, bytes_remaining):

    size = stream.filesize
    p = 0
    while p <= 100:
        progress = p
        print str(p)+'%'
        p = percent(bytes_remaining, size)

这将计算文件大小和剩余字节数之间的百分比。
def percent(self, tem, total):
        perc = (float(tem) / float(total)) * float(100)
        return perc

1
没有任何输出... :( - Chris P
8
现在出现 TypeError: progress_function() 缺少一个必需的位置参数 'bytes_remaining'。 - Chris P
3
chunkfile_handle参数是用来做什么的? - nonimportant
你为什么要使用Python 2.x版本? - nonimportant
1
出现错误:TypeError: progress_function()缺少2个必需的位置参数:'file_handle'和'bytes_remaining'。 - Khan Saad

5

这是一些有趣的东西!

我们可以使用以下代码模拟 Linux 下载动画:

def progress_function(chunk, file_handle, bytes_remaining):
    global filesize
    current = ((filesize - bytes_remaining)/filesize)
    percent = ('{0:.1f}').format(current*100)
    progress = int(50*current)
    status = '█' * progress + '-' * (50 - progress)
    sys.stdout.write(' ↳ |{bar}| {percent}%\r'.format(bar=status, percent=percent))
    sys.stdout.flush()

yt_obj = YouTube('<<some youtube video URL>>', on_progress_callback=progress_function)

输出结果如下:

↳ |██████████████████████████████████----------------| 68.4%

祝玩得开心!!


要改变外观,我认为你应该修改display_progress_bar函数。 - Hosein Rahnama

4

我知道这个问题已经有答案了,但是我看到这个问题时,我的进度从100倒数到0。因为我想用百分比值来填充进度条,所以我不能使用这个。

所以我想出了这个解决方案:

def progress_func(self, stream, chunk, file_handle,bytes_remaining):
    size = self.video.filesize
    progress = (float(abs(bytes_remaining-size)/size))*float(100))
    self.loadbar.setValue(progress)

加载条是来自PyQt5的进度条。 希望这能对某些人有所帮助。

4
回调函数有三个参数,而不是四个: streamchunkbytes_remaining

为什么?最新版本的文档显示这三个参数:on_progress(chunk: bytes, file_handler: BinaryIO, bytes_remaining: int)。我使用了流(stream)和字节剩余(bytes_remaining),它可以工作,但我不明白为什么! - Maxouille

3
这里是稍微高级一些的版本。
def on_progress(vid, chunk, bytes_remaining):
    total_size = vid.filesize
    bytes_downloaded = total_size - bytes_remaining
    percentage_of_completion = bytes_downloaded / total_size * 100
    totalsz = (total_size/1024)/1024
    totalsz = round(totalsz,1)
    remain = (bytes_remaining / 1024) / 1024
    remain = round(remain, 1)
    dwnd = (bytes_downloaded / 1024) / 1024
    dwnd = round(dwnd, 1)
    percentage_of_completion = round(percentage_of_completion,2)

    #print(f'Total Size: {totalsz} MB')
    print(f'Download Progress: {percentage_of_completion}%, Total Size:{totalsz} MB, Downloaded: {dwnd} MB, Remaining:{remain} MB')

yt.register_on_progress_callback(on_progress)


2

较为简短的选项:

yt = YouTube(video_link, on_progress_callback=progress_function)

video = yt.streams.first() # or whatever 

# Prints something like "15.555% done..." 
def progress_function(stream, chunk, file_handle, bytes_remaining):
    print(round((1-bytes_remaining/video.filesize)*100, 3), '% done...')

当然,你可以限制进度输出,例如,仅输出10%,20%,30%等数值... - 只需用所需的if语句包围print语句即可。


1
from pytube import Playlist
from pytube import YouTube

previousprogress = 0
def on_progress(stream, chunk, bytes_remaining):
    global previousprogress
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining 

    liveprogress = (int)(bytes_downloaded / total_size * 100)
    if liveprogress > previousprogress:
        previousprogress = liveprogress
        print(liveprogress)


yt = YouTube('https://www.youtube.com/watch?v=4zqKJBxRyuo&ab_channel=SleepEasyRelax-KeithSmith')
yt.register_on_progress_callback(on_progress)
yt.streams.filter(only_audio=True).first().download()

0
你可以像这样添加进度条。忽略任何愚蠢的类型错误(如果有的话)。
pytube.request.default_range_size = 1048576    # this is for chunck size, 1MB size



yt = YouTube(url)
video = yt.streams.first()

video.download(<whatever>)


def progress_callback(stream, chunk, bytes_remaining):
    size = video.filesize
    progress = int(((size - bytes_remaining) / size) * 100)
    print(progress)
    # do call progress bar from GUI here


def complete_callback(stream, file_handle):
    print("downloading finished")
    # progress bar stop call from GUI here


yt.register_on_progress_callback(progress_callback)
yt.register_on_complete_callback(complete_callback)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接