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

95 views Asked by At

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.

2

There are 2 answers

4
simbabque On BEST ANSWER

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 );
2
LaintalAy On

There's a second method, from @simbabque documentation reference, that I think you should try:

 $mech->find_all_links_dom %options

 print $_->{innerHTML} . "\n"
     for $mech->find_all_links_dom( text_regex => qr/google/i );

Finds all matching linky DOM nodes in the document. The options are documented in ->find_link_dom.

Returns them as list or an array reference, depending on context.

This defaults to not look through child frames.