user411103
user411103

Reputation:

Retrieve <TD> text using WATIR

I am using WATIR for automated testing, and I need to copy in a variable the value of a rate. In the example below (from webpage source code), I need that variable myrate has value 2.595. I know how to retrieve value from <input> or <span> (see below), but not directly from a <td>. Any help? Thanks

<TABLE>
<TR>
    <TD></TD>
    <TD>Rate</TD>
    <TD>2.595</TD>
</TR>
</TABLE>

For a <span> I use this code:

raRetrieved = browser.span(:name => 'myForm.raNumber').text

Upvotes: 4

Views: 9136

Answers (3)

user411103
user411103

Reputation:

If this helps to anyone who is having the same issue, it is working for me like this:

browser.td(:text => "Rate").parent.cell(:index, 2).text

Thank you all

Upvotes: 1

Chuck van der Linden
Chuck van der Linden

Reputation: 6660

try this, find the row you want using a regular expression to match a row that contains the word 'Rate', then get the text of the third cell in the row.

myrate = browser.tr(:text, /Rate/).td(:index => 2).text
 #or you can use the more user-friendly aliases for those tags
myrate = browser.row(:text, /Rate/).cell(:index => 2).text

If the word 'Rate' might appear elsewhere in other textin that table, but is always just the only entry in the second cell of the row you want, then find the cell with that exact text, use the parent method to locate the row that holds that cell , and then get the text from the third cell.

myrate = browser.cell(:text, 'Rate').parent.cell(:index => 2).text

use of .cell & .row vs .td & .tr is up to you, some people prefer the tags, others like the more descriptive names. Use whatever you feel makes the code the most readable for you or others who will work with it.

Note: code above presumes use of Watir-Webdriver, or Watir 2.x which both use zero based indexing. For older versions of Watir, change the index values to 3

And for the record I totally agree with comments of others about the lack of testability of the code sample you posted. it's horrid. Asking for something to locate the proper elements, such as ID values or Names is not out of line in terms of making the page easier to test.

Upvotes: 8

Željko Filipin
Željko Filipin

Reputation: 57312

Try this:

browser.td(how, what).text

The problem here is that table, tr and td tags do not have any attributes. You can try something like this (not tested):

browser.table[0][2].text

Upvotes: 2

Related Questions