Aks..
Aks..

Reputation: 1393

Get entire column text of a table using Watir

I know that using the following code we can get the entire row text in WATIR

# row 2 - entire text
table1 = browser.table(:id => "table")
puts table1[1].text

How can we get the entire column text like this?

Upvotes: 2

Views: 4295

Answers (2)

Justin Ko
Justin Ko

Reputation: 46836

There are some built-in methods to help get column data, however it is different between Watir-Webdriver and Watir-Classic.

Let us assume that we are working with the table:

<table>
  <tr>
    <td>1a</td>
    <td>1b</td>
  </tr>
  <tr>
    <td>2a</td>
    <td>2b</td>
  </tr>
</table>

Solution - Watir-Webdriver and Watir-Classic

The Table class has a strings method that returns the text of the table as a 2D array. The array is of rows, but you can use transpose to get it to be columns.

columns = browser.table(:id => "table").strings.transpose
p columns[0]
#=> ["1a", "2a"]
p columns[1]
#=> ["1b", "2b"]

Solution - Watir-Classic

In Watir-Classic, the Table class also has a built-in column_values method, which means you can simply do:

p browser.table(:id => "table").column_values(0)
#=> ["1a", "2a"]
p browser.table(:id => "table").column_values(1)
#=> ["1b", "2b"]

Solution - Iteration

You can of course also iterate through each row and collect the cell in each column:

p browser.table(:id => "table").trs.collect{ |tr| tr[0].text }
#=> ["1a", "2a"]
p browser.table(:id => "table").trs.collect{ |tr| tr[1].text }
#=> ["1b", "2b"]

Upvotes: 8

Aks..
Aks..

Reputation: 1393

Not sure if there's any ready API. So here's the workaround :

table1 = browser.table(:id => "table")
row_count = table1.rows.length
for k in 0..row_count-1
  puts table1[k][1].text
end

Upvotes: 1

Related Questions