Watir无法找到集合中的元素

时间:2016-04-04 09:52:33

标签: ruby watir watir-webdriver

我刚刚遇到这个问题,处理集合中的元素有点困难。在我的情况下,我试图通过表解析并检查列的单元格中包含的值。 这是代码:

def check_cells_values(table, cell_index)
 table.rows.each do |row|
   row.cells[cell_index].text.should == some_value
 end
end

在" row.cells [cell_index] .text.should == some_value"测试失败并出现此错误:

Watir::Exception::UnknownObjectException: unable to locate element, using {:element=>#<Selenium::WebDriver::Element:0x7b40a27fd80f640e id="{af57e857-69ed-5345-a4ae-5ab80dff364a}">}

只需遍历行并从每行输出文本就足够了。在某些行(随机)之后,它会失败并显示相同的消息。

我找到了这个链接(https://jkotests.wordpress.com/unable-to-locate-element/),贾斯汀在这里提到了这个问题,但我没有发现任何与元素集合相关的东西。

更新: 这是我正在解析的一个表的行示例。

  <tr class="dataRow even  first" onclick="highlightElem(this)" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
      <td class="dataCell  " id="someid3" colspan="1"><a href="/url">8882</a></td>
      <td class="dataCell  " id="someid2" colspan="1">
           <label>Some kind of service</label></td>
      <td class="dataCell  " id="someid6" colspan="1"></td><td class="dataCell  " id="someid7" colspan="1"><input class="btn" id="someid8" onclick="A4J.AJAX.Submit('pgToolOffer:pgForm',event,{'similarityGroupingId':'someid8','oncomplete':function(request,event,data){UpdatePopupPosition();},'parameters':{'selectedRatePlan':'Annual','selectedOfferFriendlyName':'Some service 50$','someid8':'someid8','selectedProduct':'Service Descrition','selectedOfferCode':'product\duration\x2DDG275'} } );return false;" value="Show Offer Details" type="button"></td>
  </tr>

2 个答案:

答案 0 :(得分:1)

我怀疑页面上的客户端javascript代码仍在构建表,或者在自动化与之交互时更新它。

作为一种尝试查看是否是这种情况的方法,我会尝试在该代码之前简单地插入一个大等待,例如10或15秒,以查看它是否开始表现。我通常避免使用睡眠同步(因为它们太短(flakey测试)或太长(测试速度慢)。但是对于故障排除和调试,它可以是识别同步问题的快速方法。

如果这有所不同,您知道自己有同步问题,那么可以更深入地了解如何在页面完成更新时告诉您。通常这意味着要查找在更新结束时创建的某个元素,并让代码等到它继续之前在页面上看到该元素。对于使用jQuery的页面,您还可以获取jQuery.active值(打开ajax请求)并等待它变为零并保持半秒左右,作为一种告诉页面完成客户端的方式ajax请求并且可能处于适当的状态以便继续进行测试。

答案 1 :(得分:0)

第一个选项(严格代码):

table.rows.each do |row| #We'll take each row
  cell = row[given_index] #We'll take one cell of the taken row
  puts cell.text #We'll do some stuff with the text of the cell
end

第二个选项(让我们不断尝试重新定位表格):

i = 0
table.rows.length.times do
  table = b.table(id: "table")
  puts table[i][given_index].text
  i = i+1
end