2

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.

simbabque
  • 50,588
  • 8
  • 69
  • 121
Bill
  • 1,169
  • 2
  • 19
  • 41

2 Answers2

2

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 );
simbabque
  • 50,588
  • 8
  • 69
  • 121
  • Thanks for the help. Another question that is somewhat related. Is there a way to search on 'Title' instead of of text? – Bill Apr 06 '16 at 14:10
  • @Bill I don't see that there's a built-in way to do that. See https://metacpan.org/source/CORION/WWW-Mechanize-Firefox-0.78/lib/WWW/Mechanize/Firefox.pm#L2317. I guess you'd have to do that with your own XPath expression. If you have trouble with that, ask a new question please. – simbabque Apr 06 '16 at 14:15
  • @Bill did you find a way to do the `title` thing? – simbabque Apr 13 '16 at 07:47
  • I didn't. I went a different direction with it. – Bill Apr 13 '16 at 13:29
1

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.

LaintalAy
  • 1,134
  • 1
  • 16
  • 26
  • Good spot. That's probably the more concise option, though the interface is a bit questionable. But please [edit] your answer and remove the first line. This is fine as an answer, no need to apologize. You can add a working example though. – simbabque Apr 06 '16 at 13:55
  • Yep, the interface and documentation leave room for improvement. – LaintalAy Apr 06 '16 at 14:08