Search code examples
perlfilewww-mechanize

How can I download a file using WWW::Mechanize or any Perl module?


Is there a way in WWW::Mechanize or any Perl module to read on a file after accessing a website. For example, I clicked a button 'Receive', and a file (.txt) will appear containing a message. How will I be able to read the content? Answers are very much appreciated.. I've been working on this for days,, Also, I tried all the possibilities. Can anyone help? If you can give me an idea please? :)

Here is a part of my code:

...

my $username = "admin";<br>
my $password = "12345";<br>

my $url = "http://...do_gsm_sms.cgi";

my $mech = WWW::Mechanize->new(autocheck => 1, quiet => 0, agent_alias =>$login_agent, cookie_jar => $cookie_jar);

$mech->credentials($username, $password);<br>
$mech->get($url);

$mech->success() or die "Can't fetch the Requested page";<br>

print "OK! \n"; #This works <br> 

$mech->form_number(1);

$mech->click()

;

After this, 'Downloads' dialog box will appear so I can save the file (but I can also set the default to open it immediately instead of saving). Question is, how can I read the content of this file?

..


Solution

  • After the click (assuming that's doing what it's supposed to), the returned data should be stored in your $mech object. You should be able to get the file data with $mech->content(), perhaps after verifying success with $mech->status() and the type of response with $mech->content_type().

    You may find it helpful to remember that WWW::Mechanize replaces the browser; anything a browser would have done, like bringing up a download window and saving a file, doesn't actually happen, but all the information the browser would have had is accessible through WWW::Mechanize's methods.