Search code examples
perlwww-mechanize

How do I download an image file from a website using WWW::Mechanize?


I try to download the image from the server. I try so far,

use warnings;
use strict; 
use WWW::Mechanize;

my $sequence = "MIPTLAAEPRKPARPPLPVRRESREEPVDAVIVGTGAGGAPLLARLAQAGLKVVALEAGNHWDPAADFATDEREQNKLFWFDERLSAGADPLAFGRNNSGIGVGGSTLHYTAYVPRPQPDDFRLYSDFGVGEDWPIGYGDLEPYFDELECFLGVSGPSPYPWGPARTPYPLAPMPLNAAAQLMARGCAALGLRTSPAANAVLSAPYFQSGVGWRSPCTNRGFCQAGCTTGGKAGMDVTFIPLALAHGAEVRSGAFVTRIETDRAGRVTGVVYVREGREERQRCRTLFLAAGAIETPRLLLLNGLANQSGEVGRNFMAHPGLQLWGQFSEATRPFKGVPGSLISEDTHRPKDADFAGGYLLQSIGVMPVTYATQTARGGGLWGEKLQSHMHGYNHTAGINILGECLPYAHNYLELSDEPDQRGLPKPRIHFSNGKNERRLRDHAEALMRRIWEAAGAQAVWTFERNAHTIGTCRMGADPKRAVVDPEGRAFDVPNLYIIDNSVFPSALSVNPALTIMALSLRTADRFIERTQRGEY";

my $mech = WWW::Mechanize -> new;
$mech->get('https://npsa-prabi.ibcp.fr/cgi-bin/npsa_automat.pl?page=/NPSA/npsa_sopma.html');
    $mech->submit_form(
        form_number => 1,
        fields => {
        'notice' => $sequence,
        },
    );


$mech->find_image( alt_regex => qr/.+sopma2.gif/ );
open (FH, ">soi.gif");
binmode (FH);
print FH $mech;

The image tag was like this:

<img align="TOP" src="/tmp/e3a3c2b34201.sopma2.gif">

I already have the link to the image parsed from the website, but I want to download this image. How can I do it?


Solution

  • use LWP::Simple with WWW::Mechanize.

    use WWW::Mechanize;
    use LWP::Simple;
    my $sequence = "MIPTLAA......";
    
    my $mech = WWW::Mechanize -> new;
    $mech->get('https://npsa-prabi.ibcp.fr/cgi-bin/npsa_automat.pl?page=/NPSA/npsa_sopma.html');
        $mech->submit_form(
            form_number => 1,
            fields => {
            'notice' => $sequence,
            },
        );
    
    my $cont = $mech->content;  
    ($img) = $cont =~m/SRC=(.+sopma2\.gif)/g; 
    $urL = "https://npsa-prabi.ibcp.fr/$img";
    getstore($urL,"soi.gif");
    

    $img stores the url of the image

    Then save the image by using getstore method from the LWP::Simple

    It is not good idea. See the @simbabque answer. But it give the result what you need.