0

Using the following HTML I am trying to randomly select one of the href links

<div class="field">
<a href="/destinations/caribbean/british-virgin-islands/tortola-power-charter/availability">Check availability</a>
</div>
</div>
</div>
</div>
</article>
</div>
<div class="views-row views-row-3 views-row-odd views-row-last">
<article id="node-cruise-47" class="node node-cruise node-search-result node-cruise-search-result node-published node-not-promoted node-not-sticky author-admin odd clearfix s-search-result" itemscope="" itemtype="http://schema.org/Product">
<div class="search-result-inner clearfix">
<div class="s-search-result--left">
<div class="s-search-result--middle">
<div class="s-search-result--right">
<div class="field field-name-field-price field-type-number-decimal field-label-inline clearfix price-summary">
<div class="field field-name-field-departure-duration field-type-number-integer field-label-hidden price-conditions primary-condition">Based on 7 nights, yacht only</div>
<div class="availability-button-wrapper-search">
<div class="field">
<a href="/destinations/caribbean/british-virgin-islands/tortola-crewed-charter/availability">Check availability</a>

Note that several href links are present on the page not just these 2. I am using the following code

b.links(:xpath => '//div[@class="field"]/a').click 

However I get:

"undefined method `click' for #<Watir::AnchorCollection:0x2ba1858> (NoMethodError)"
smathy
  • 26,283
  • 5
  • 48
  • 68
rubytester
  • 37
  • 7
  • You mean you're trying to randomly click a link on a page programatically? Does it have to be done using Ruby? – pabrams Jan 04 '16 at 20:52

1 Answers1

4

Try to pick randomly from array

b.links(:xpath => '//div[@class="field"]/a').to_a.sample.click
Community
  • 1
  • 1
Artem
  • 823
  • 8
  • 14
  • Thanks. Can you please tell me how to_a.sample works? Still fairly new to this – rubytester Jan 04 '16 at 22:06
  • [Sample](http://ruby-doc.org/core-2.2.0/Array.html#method-i-sample) is stadard method of Array, [to_a](http://www.rubydoc.info/gems/watir-webdriver/Watir/ElementCollection#to_a-instance_method) allows to use collection as array – Artem Jan 04 '16 at 22:18
  • @Artem maybe nit-picky but to_a changes the collection into an array and returns it. It does not use the collection as an array. http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-to_a The above may not be ideal either since a big page with a lot of links may result in double the work of collecting all the links, translating it to an array & then using sample. You may as well count the size of the collection & use a random number gen to select one of item in the collection. If the op is looking for a generalized sanity test check out https://github.com/marmelab/gremlins.js – matic Jan 06 '16 at 18:01