Search code examples
perlwww-mechanize

How to click a button with its value with WWW::Mechanize


I am trying to click a button using a Perl script with the Mechanize module. However, the name and the position of the button always changes, so I want to click it by using its value, but I could not find how to do it.

The button is like this:

<input class="submit good" name="R_HCWE" value="CLICK HERE" type="submit">

I cannot use simply the submit() method, because there is another button to submit the form that belongs to class "submit bad".


Solution

  • Use the find_all_submits method to find the button, then click it:

    #!/usr/bin/perl
    use warnings;
    use strict;
    use feature qw{ say };
    
    use WWW::Mechanize;
    
    my $mech = 'WWW::Mechanize'->new;
    $mech->get('http://search.cpan.org/perldoc/WWW::Mechanize');
    $mech->update_html(<< '__HTML__');
    
    <html>
    <body>
    <form action="/1.pl">
    <input class="submit bad" name="R_ACWE" value="DO NOT CLICK HERE" type="submit">
    <input class="submit good" name="R_HCWE" value="CLICK HERE" type="submit">
    <form>
    </body>
    </html>
    
    __HTML__
    
    my $button = ($mech->find_all_submits(class => 'submit good'))[0];
    say $button->class;