Ruby Watir从表中选择文本

时间:2013-10-30 16:51:08

标签: ruby watir

我有一个标签表,我试图从“Active”列中获取正在运行的各种服务的值。

Services
    Service                    Active
    SERVICE1                   YES
    SERVICE2                   NO
    SERVICE3                   YES

我希望从表中使用这样的东西。但这似乎对我不起作用。目标是选择其中一个服务并查明它是否为活动是或否并将其放入变量中。在以前的答案中,你们对我帮助很大,我非常感谢你的帮助和意见。

browser.td(:text => "SERVICE1").parent.td(:index => 1).flash 

当我尝试使用上面的代码

时,我收到这样的错误
/home/bill/.rvm/gems/ruby-1.9.2-p320@vts_automated/gems/watir-webdriver-0.6.4/lib/watir-webdriver/elements/element.rb:490:in `assert_exists': unable to locate element, using {:id=>"services", :tag_name=>"td"} (Watir::Exception::UnknownObjectException)

我的HTML代码看起来像这样

<table class="tabbed_table" cellspacing="5">
<tbody>
<tr>
<td>
<h2>Appliance</h2>
<dl class="table-display">
<dt class="wide">Product version: </dt>
<dd class="wide">xxxxx</dd>
<dt class="wide">Serial number:</dt>
<dd class="wide">xxxxxx</dd>
<dt class="wide">System Time:</dt>
<dd class="wide">Wednesday, October 30, 2013 02:02PM CDT</dd>
</dl>
</td>
<td>
<h2>Services</h2>
<table id="services">
<tbody>
<tr>
<th>Service</th>
<th>Active</th>
</tr>
<tr class="alt">
<td class="no_bg">SERVICE1</td>
<td class="no_bg">YES</td>
</tr>
<tr class="normal">
<td class="no_bg"> SERVICE2 </td>
<td class="no_bg">NO</td>
</tr>
<tr class="alt">
<td class="no_bg"> SERVICE3 </td>
<td class="no_bg">YES</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>

1 个答案:

答案 0 :(得分:0)

一种方法是从表中collect the cells创建一个哈希来存储数据,然后使用each_slice方法将数据分配给哈希。此时,您应该拥有所需的数据,并可以根据您的需要进行操作。例如:

# get cells from table(:id => "services") 

cells = browser.table(:id => "services").tds

# create hash

service_active = {}

# iterate over cells variable using each_slice method and assign keys/values to has

cells.each_slice(2) do |slice|
  service_active["#{slice[0]}"] = slice[1]
end

# hash with data

service_active.each {|k,v| puts "the value of #{k} is #{v}"}

#=> the value of Service is Active
#=> the value of SERVICE1 is YES
#=> the value of SERVICE2 is YES
#=> the value of SERVICE3 is YES