从文档http://www.rubydoc.info/gems/watir-webdriver/0.6.11/Watir/ElementCollection#each-instance_method中删除示例,我试图单击页面上具有相同类的每个元素。
这是我到目前为止所提出的代码片段:
@b.divs(:class => 'portal-thumbnail-card').each do |div|
@b.div(:class => 'portal-thumbnail-card').click
puts 'foo'
# my puts statement outputs 'foo' 6 times (matches the number of elements with that class)
# right now this only clicks on the FIRST element, having issues with the other part :(
end
即使这不涉及任何页面重新加载,是否可以单击操作?
答案 0 :(得分:1)
问题是您在循环的每次迭代期间定位div
以进行单击。在英语中,您的代码实际上说,“对于每个div
元素,使用”portal-thumbnail-card“类,请单击页面上第一个{portal,thumbnail-portal'的div
。”
您真正想要做的是点击每次迭代主题的div
元素:
@b.divs(:class => 'portal-thumbnail-card').each do |div|
div.click
puts 'foo'
end
答案 1 :(得分:1)
divs
方法返回Watir::DivCollection
,它是Watir::Div
个对象的集合。例如:
require 'watir-webdriver'
b = Watir::Browser.new
b.goto('http://example.org')
divs = b.divs
puts divs.class
#=> Watir::DivCollection
divs.each { |d| puts d.class}
#=> Watir::Div
所以 - 在你的迭代器中 - 你想引用块局部变量(即div.click
)而不是浏览器的实例变量(即@b.div(:class => 'portal-thumbnail-card').click
)
答案 2 :(得分:0)
使用 flash 方法查看您尝试点击的元素
require 'watir-webdriver'
browser = Watir::Browser.new
browser.goto "data:text/html,#{DATA.read}"
browser.divs(:class => 'portal-thumbnail-card').each do |div|
# browser.div(:class => 'portal-thumbnail-card').flash #you variant
div.flash #correct variant
puts 'foo'
end
browser.close
__END__
<html>
<div class='portal-thumbnail-card'>
<button id="button1">Button 1</button>
</div>
<div class='portal-thumbnail-card'>
<button id="button2">Button 2</button>
</div>
<div class='portal-thumbnail-card'>
<button id="button3">Button 3</button>
</div>
<div class='portal-thumbnail-card'>
<button id="button4">Button 4</button>
</div>
<div class='portal-thumbnail-card'>
<button id="button5">Button 5</button>
</div>
</html>