depojones has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I'm scrapping a site and the links have same class name,e.g:
<a class="nav" href="index.html">&nbsp;&nbsp;Home&nbsp;&nbsp;</a> <a class="nav" href="about.html">&nbsp;&nbsp;About us&nbsp;&nbsp;</a> <a class="nav" href="contact.html">&nbsp;&nbsp;Contact us&nbsp;&nbsp;< +/a>
Xpath is identifying more than one element for class name "nav"
$mech->click({xpath => '//a[@class="nav"]', synchronize=>0, });
My question is, how do I click the nth tag (contact us) from the example above? Thanks

Replies are listed 'Best First'.
Re: Mechanize Firefox xpath link with same name
by Corion (Patriarch) on Jul 15, 2014 at 12:42 UTC

    You can add an index to XPath queries if you want the nth element:

    //parent/a[@class="nav"][4]

    Note that the following does not work because numbering is according to parent/ancestor, not in the results:

    //a[@class="nav"][4]

    If you don't have a suitable common ancestor, you will have to find the element by using the text() function or extract the element using Perl:

    my @nav= $mech->xpath('//a[@class="nav"]'); $mech->click( $nav[3] );
      Thanks for your prompt reply. The example you provided worked as expected. Thank you once again!