3
votes

I have the following DOM setup and I'm trying to click each/every link using watir-webdriver. Keep in mind that both 'Random Number X' and 'Random Name X' are random and can not be used to come up with the solution.

<div class="container">
<ul>
<li id="Random Number 1"><a href="#">Random Name 1</a></li>
<li id="Random Number 2"><a href="#">Random Name 2</a></li>
<li id="Random Number 3"><a href="#">Random Name 3</a></li>
</ul>
</div>
3

3 Answers

8
votes

Something like:

browser.div(:class=>"container").links.each do | link | 
  link.click 
  browser.back
end
2
votes

You have to store all the links in an Array or structure, and then you will be able to click on all the links of a web page or a div or any element.

link = Array.new
i = 0
browser.div(:class, "container").links.each do |li|
link[i] = l.text
i = i + 1
end

li.each do |visit|
b.link(:text, visit).click
b.back
end

This is required because if you are not storing the links in to array then with the simple loop will click on first link only and when it will execute browser.back, it will not get the value of second link to click as every time cache will be cleared.

1
votes

You could also try:

browser.div(:class, 'container').as.each do |x|
    x.click
    browser.back
end

or to hit an individual link try one of the following:

browser.div(:class, 'containter').as[0].click  #This is for the first link.   
browser.div(:class, 'containter').a(:text, 'Random Name 1').click