regexperlmechanizewww-mechanize-firefox

How do I find the second link occurance using WWW::Mechanize::Firefox and find_link_dom in Perl?


I am using find_link_dom and it's working... to find the first link that matches. I need to find the second. Here is my line:

my $link = $mech->find_link_dom ( text_regex => 'abc' );

Is there a way for this command to return the second link that matches?

And before someone comment that I need to change my search criteria, the text is the same. The only thing different is the url and I don't know just from the url which should be picked. I need the second link that match the above search.


Solution

  • The documentation says it returns objects. That's plural. There is also this piece of code. Note the for.

    print $_->{innerHTML} . "\n"
        for $mech->find_link_dom( text_contains => 'CPAN' );
    

    So you can just call it in list context to get all the found links, or just take the one you want.

    ( undef, my $link ) = $mech->find_link_dom ( text_regex => 'abc' );
    

    That should give you the second one.

    Alternatively, grab all of them and output, to see what's going on.

    use Data::Printer;
    
    my @links = $mech->find_link_dom ( text_regex => 'abc' );
    p @links
    

    Or, you can use the option n, which is a 1-based index.

    my $second_link = $mech->find_link_dom( text_regex => 'abc', n => 2 );