0

When using WWW::Mechanize::Firefox to select an item, is it possible to iterate through a number of selectors that have the same name?

I use the following code:

my $un = $mech->selector('input.normal', single => 1);

The response is 2 elements found for CSS selector. Is there a way to use XPath or a better method, or is it possible to loop through the results?

Bonus point: typing into the inputs even though it is not in form elements (ie. uses JavaScript)

Borodin
  • 126,100
  • 9
  • 70
  • 144
tread
  • 10,133
  • 17
  • 95
  • 170
  • I don't understand your "bonus point". Please explain – Borodin Mar 08 '13 at 09:36
  • I was unsure how to enter data into the input (that isn't in a form) so I couldn't use "submit_form". But I used the doc and saw you could use ->field([selector], value => x). So bonus point is gone. Thanks Borodin I appreciate your assistance. There is a problem now that I can't select the second input on the page, using "two => 1"...so I'm going to have to use arrays unless you say different. – tread Mar 08 '13 at 09:47
  • You're still misunderstanding the purpose of the option parameter. The method *always* returns all the elements that match the selector. The option specifies the conditions when an exception will be thrown according to the number of matches found. `one` says that there must be at least one match, `single` says that there must be exactly one match, and `maybe` requires no matches or one match: more than one match is an error. There is no `two`. To access the second `` element, just use `$inputs[1]` in my example. – Borodin Mar 08 '13 at 10:25
  • ok, thanks it makes more sense now. Hah, a direct reference is much better for this example...I was using a foreach – tread Mar 08 '13 at 11:20

2 Answers2

2

With the single option you have specified that there should be exactly one element that matches the selector. That is why you get an error message when it finds two matches.

The method will return a list of matches, and you can either use one => 1 in place of single => 1, which will throw van error if there isn't at least one match, or you can leave the option out altogether, when it will simply return all that it finds.

my @inputs = $mech->selector('input.normal')

will fill the array @inputs with a list of matching <input> elements, however many there are.

Borodin
  • 126,100
  • 9
  • 70
  • 144
1

Module documentation contain these examples:

my $link = $mech->xpath('//a[id="clickme"]', one => 1);
# croaks if there is no link or more than one link found

my @para = $mech->xpath('//p');
# Collects all paragraphs
Borodin
  • 126,100
  • 9
  • 70
  • 144
gangabass
  • 10,607
  • 2
  • 23
  • 35