How to add a progress bar to WWW :: Mechanize?
I have the following code:
$mech->get($someurl, ":content_file" => "$i.flv"); So, I get the contents of the url and save it as a flv file. I would like to print every second or so, how many downloads are left. Is there any way to do this in WWW :: Mechanize?
Many thanks to Peter Kovacs answer for leading me to the correct answer. This turned out to be a little more complicated than I expected, although I therefore decided (horror) to answer my own question.
As Peter showed, I can set the callback as follows:
$m->get($u, ":content_cb" => \&callback); But now I canβt save the content using the value: content_file, because I can only select one of them. The callback function passes the data, and I ended up writing this to a file.
I also get a response object that contains the total size of the content, as friedo pointed out. Thus, by storing the total amount of content received so far and dividing it by the total content, I can find out what percentage 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 this helps someone.
WWW::Mechanize says the get method is a "good" overload of the LWP :: UserAgent get . Looking at the documents for LWP :: UserAgent, you can provide the content_cb key, which is called with each fragment of the downloaded file:
$mech->get( $someurl, ":content_cb" => \&callback ); sub callback { my( $data, $response, $proto ) = @_; # save $data to $i.flv # print download notification }