Forwarding Forwarding - 1 year ago 56
Ruby Question

How to access href of array of links in a loop using watir-webdriver

I've got an array of certain

elements like this:

array = => 'foo')

I try to go to the links like this:

$i = 0
while $i < num do
browser.goto array[$i].href
$i += 1

Which works the for the first loop, but not for the second. Why is this happening? If I do

puts array[1].href
puts array[2].href
puts array[-1].href


browser.goto array[$i].href

it shows all the links on the first loop in terminal window.

Answer Source

Someone who knows this better than I do will need to verify / clarify. My understanding is that elements are given references when the page is loaded. On loading a new page you are building all new references, even if it looks like the same link on each page.

You are storing a reference to that element and then asking it to go ahead and pull the href attribute from it. It works the first time, as the element still exists. Once the new page has loaded it no longer exists. The request to pull the attribute fails.

If all you care about are the hrefs there's a shorter, more Ruby way of doing it.

array = [] => 'foo').each { |link|
  array << link.href

array.each { |link| 
  browser.goto link

By cramming the links into the array we don't have to worry about stale references.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download