如何点击变量链接?

时间:2015-04-14 09:12:10

标签: ruby selenium-webdriver watir watir-webdriver

参考ŽeljkoFilipin的回答 How do I retrieve a custom attribute in watir?

我有很多链接,例如:

<a href="//stackoverflow.com"
  title="professional and enthusiast programmers">Stack Overflow</a>
<a href="//programmers.stackexchange.com" 
  title="professional programmers interested in conceptual questions about software development">Programmers</a>

我已将链接存储在数组中;我需要点击个别链接。

browser.link(:href => /stackoverflow/).click

而不是“stackoverflow”,我想运行我的数组(即用数组变量替换):

browser.link(:href => /array[i]/).click

任何人都可以告诉我如何实现这一目标吗?

2 个答案:

答案 0 :(得分:0)

这就是你想要的吗?

  array.each { |link|
      browser.link(:href, 'link').click
    }

答案 1 :(得分:0)

这是一个人为的例子,它将循环显示href个属性列表,并将每个属性插入到一个循环中,点击每个链接:

require 'watir-webdriver'

b = Watir::Browser.new
b.goto('http://www.iana.org/domains/reserved')
arr = %W(/domains /numbers /protocols)           # an array of strings
arr.each { |el| b.link(href: "#{el}").click}

这里的技巧是插值语法:#{}。放在双引号字符串中时,#{}中的代码将被计算并插入到字符串中。例如:

# interpolate a string
str_to_insert = "world"
puts "hello #{str_to_insert}"
#=> hello world

# evaluate code before interpolation
puts "one plus two equals #{1 + 2}"
#=> one plus two equals 3