用于显示表元素详细信息的Ruby代码

时间:2017-05-24 09:29:20

标签: ruby watir ruby-watir

我有一个HTML,它以下列方式显示产品详细信息:

<div class="column">
    <h3 class="hidden-xs">Product Details</h3>
    <table class="table table-striped">
        <tbody>
            <tr class="header-row hidden-xs">
                <th>Product</th>
                <th>Duration</th>
                <th>Unit Price</th>
                <th>Price</th>
            </tr>
            <tr>
                <td>google.com</td>
                <td>1 Year</td>
                <td class="hidden-xs">$5</td>
                <td>$5</td>
            </tr>
        </tbody>
    </table>
  <div class="totals text-right">
    <p>Subtotal: $5</p>
    <p>Total: $5</p>
  </div>
</div>

Ruby代码如下:

require 'watir'

browser = Watir::Browser.new(:chrome)

browser.goto('file:///C:/Users/Ashwin/Desktop/text.html')

browser.table(:class, 'table table-striped').trs.each do |tr|
 p tr[0].text
 p tr[1].text
 p tr[2].text
 p tr[3].text
end

我以这种方式得到输出:

"Product"
"Duration"
"Unit Price"
"Price"
"google.com"
"1 Year"
"$5"
"$5"

但我希望细节显示如下:

Product    : google.com
Duration   : 1 Year
Unit Price : $5
Price      : $5

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

该表看起来非常简单,因此您可以使用Table#strings方法将表转换为字符串数组。然后,您可以使用每个行值输出每个列标题。

# Get the table you want to work with
table = browser.table(class: 'table table-striped')

# Get the text of the table
rows = table.strings

# Get the column headers and determine the longest one
header = rows.shift    
column_width = header.max { |a, b| a.length <=> b.length }.length

# Loop through the data rows and output the header/value
rows.each do |row|
  header.zip(row) do |header, value|
    puts "#{header.ljust(column_width)} : #{value}"
  end
end
#=> Product    : google.com
#=> Duration   : 1 Year
#=> Unit Price : $5
#=> Price      : $5

答案 1 :(得分:0)

此代码仅适用于具有两行的给定表

require 'watir'

browser = Watir::Browser.new(:chrome)

browser.goto('file:///C:/Users/Ashwin/Desktop/text.html')

browser.table(:class, 'table table-striped').rows.each_with_index do |row,index|  
  if index.eql?0
    firstRow=row
    next
  end
  p firstRow[0].text+":"+row[0].text
  p firstRow[1].text+":"+row[1].text
  p firstRow[2].text+":"+row[2].text
  p firstRow[3].text+":"+row[3].text
end