当存在具有相同显示文本的其他链接时,使用Watir单击特定链接
所以我有一张桌子看起来就像那里有书籍清单,在第一栏中有两个链接,查看和删除,每本书。
我希望能够使用Watir找到具有指定书名的行,然后单击该书的该视图按钮。
这是我到目前为止所拥有的
And /^click on View link of "(.*)" on the result set table$/ do |cell_name| cellButton("submit.view", cell_name, "") end # # And /^click on Delete link of "(.*)" on the result set table with no_wait$/ do |cell_name| cellButton("submit.delete", cell_name, "no_wait") end # # def cellButton(submit_type, s_name, s_wait_type) c_found = 0 @browser.tables do |tbl| tbl.rows do |r| r.each do |c| if c.text.to_s.matches(s_name) c_found += 1 end break if c_found > 0 end if c_found > 0 if s_wait_type == "no_wait" r.button(:name, submit_type).click_no_wait else r.button(:name, submit_type).click end end break if c_found > 0 end end end
这是特定视图按钮的html
[ ]
[ ] book title more tds
运行脚本时没有错误,但是没有按下视图链接。
我使用的是Watir 4.0,Ruby 1.9.3和Cucumber 1.3.3
假设你的表格html是:
book title 1 book title 2
然后您可以看到书名和视图按钮与其父行(tr)相关。
通过兄弟访问元素的最简单方法是:
- 找到具有唯一属性的元素; 在这种情况下,带有书名的td。
- 使用
parent
方法获取父元素(即tr)。 - 获取与父元素相关的所需元素(即行中的第一个视图按钮)。
例如,要获取“书名2”的“查看”按钮,您可以执行以下操作:
book_title = 'book title 2' table = browser.table(:id => 'my_table') book_row = table.td(:text => book_title).parent book_row.button(:value => 'View').click
上述解决方案将在任何列中查找书名。 如果书名标题文本仅在一列中,则可以。 如果文本可能在另一列中,您将要执行以下操作:
book_title = 'book title 2' table = browser.table(:id => 'my_table') book_row = table.trs.find{ |tr| tr.td(:index => 1).text == book_title } book_row.button(:value => 'View').click
可能会有一个更清洁的方式,但我会试一试。
假设这个简化的HTML(即带有链接而不是按钮的2列表):
View Title One View Title Two View Title Three
此代码应通过定位书名来实现:
title = "Title Three" trs = b.table(:id => "foo").rows row_index = 0 trs.each do |tr| tr.each do |cell| if cell.text == title b.link(:text => "View", :index => "#{row_index}").click # alternately, using the fire_event method # b.link(:text => "View", :index => "#{row_index}").fire_event("onclick") end end row_index += 1 end