如何向 WWW::Mechanize 添加进度条? [英] How can I add a progress bar to WWW::Mechanize?

查看:61
本文介绍了如何向 WWW::Mechanize 添加进度条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

$mech->get($someurl, ":content_file" => "$i.flv");

所以我正在获取一个 url 的内容并将其保存为一个 flv 文件.我想每隔一秒左右打印出剩余的下载量.在 WWW::Mechanize 中有什么方法可以做到这一点吗?

So I'm getting the contents of a url and saving it as an flv file. I'd like to print out every second or so how much of the download is remaining. Is there any way to accomplish this in WWW::Mechanize?

推荐答案

非常感谢 Peter Kovacs 的回答引导我找到正确答案.结果比我预期的要复杂一些,所以我决定(恐怖)回答我自己的问题.

Many thanks to Peter Kovacs' answer for leading me to the correct answer. It turned out to be a bit more elaborate than I'd expected though so I decided to (horror) answer my own question.

正如 Peter 所示,我可以像这样设置回调:

As Peter showed, I can set a callback like so:

$m->get($u, ":content_cb" => \&callback);

但现在我无法使用 :content_file 值保存内容,因为我只能选择两者之一.回调函数传递了数据,我最终将其写入文件.

But now I can't save the content using the :content_file value, because I can only choose one of the two. The callback function gets passed the data, and I ended up writing that to a file instead.

我还得到了一个响应对象,其中包含 Friedo 指出的内容的总大小.因此,通过保持到目前为止收到的内容总数并将其除以总内容,我可以找出已下载的内容百分比.这是完整的回调函数:

I also get a response object which contains the total size of the content as friedo pointed out. So by keeping a running total of content received so far and dividing it by the total content I can find out what percent of the content has been downloaded. Here's the full callback function:

open (VID,">$i.flv") or die "$!";
$total = 0;
sub callback
{
    my( $data, $response, $proto ) = @_;
    print VID "$data"; # write data to file
    $total+= length($data);
    $size = $response->header('Content-Length');
    print floor(($total/$size)*100),"% downloaded\n"; # print percent downloaded
}

我希望对某人有所帮助.

I hope that helps someone.

这篇关于如何向 WWW::Mechanize 添加进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆