1

How can get the text in a cell at position (row_no , col_no) of a table in Capybara? In Watir it was easy to fetch a table element and do table_element[2][3].

How can this be done in Capybara?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Aks..
  • 1,343
  • 1
  • 20
  • 42
  • 1
    have a look here - http://stackoverflow.com/questions/20526036/how-to-get-a-html-table-row-with-capybara – Arup Rakshit Aug 21 '14 at 06:52
  • Yes I have taken a look,its perfect for looping thru entire table. But what I want is exact cell data when row and column no are given. I would try avoiding traversing thru all rows and column , if possible!!The below answer by @wicz might work. – Aks.. Aug 21 '14 at 09:18

1 Answers1

4

Capybara also supports XPath for querying:

page.has_selector?(:xpath, '//table/tr[2]/td[3]')

There is this nice cheat sheet in case you want deepen your knowledge on how to traverse documents with XPath.

HTH.

wicz
  • 2,315
  • 12
  • 13
  • great, this will definitely work in Capybara. I'm just trying it out in a little different manner. And the cheatsheet is amazing!! – Aks.. Aug 21 '14 at 09:20
  • if I have the row and col no i can probabaly create a xpath string and make it general too: `def get_cell_text(row,col) xpath_string = "//table/tr[#{row}]/td[#{col}]" page.has_selector?(:xpath, xpath_string) end` But Yes will this work only assuming the table built follows the usual table row column ideology(without the tbody,tfooter etc)? – Aks.. Aug 22 '14 at 04:55
  • 2
    For these cases you can use `//table//tr/td`. See, the operator `/` means _direct_ child. The double-slash `//` means descendants, thus ignoring intermediate hierarchy. Check this [example](http://en.wikipedia.org/wiki/XPath#Examples). – wicz Aug 22 '14 at 07:33