jonsie_araki
jonsie_araki

Reputation: 221

Return array of hrefs

I need Watir to return an array of hrefs. These hrefs are all in the same div and they all have the same class. My code to grab the first href on the page looks like this:

b.div(:class => 'products').link(:class => 'product_detail_url').href

But, after that I can't find out how to loop through all available hrefs in that div.

I honestly looked all over the place, but none of the solutions I found seemed to address my specific need. Thanks for reading, hopefully someone has a solution.

Upvotes: 3

Views: 149

Answers (2)

Jarmo Pertman
Jarmo Pertman

Reputation: 1905

Or you can write it even shorter by using #map as a #collect's alias and short-block-syntax:

hrefs = b.div(:class => 'products').links(:class => 'product_detail_url').map(&:href)

Upvotes: 1

Justin Ko
Justin Ko

Reputation: 46836

Try:

b.div(:class => 'products').links(:class => 'product_detail_url').each do |link|
  puts link.href
end

Basically this iterates through a collection of links that have the specific class.

Update:

To collect all of the hrefs into an array, use the collect method:

link_arr = b.div(:class => 'products').links(:class => 'product_detail_url').collect{ |link| link.href }

Or break it into two lines for easier reading:

link_collection = b.div(:class => 'products').links(:class => 'product_detail_url')
link_arr = link_collection.collect{ |link| link.href }

Upvotes: 2

Related Questions