无法通过索引获得TD的文本

时间:2012-12-24 12:26:40

标签: watir-webdriver

我有以下代码:

<table id="table1" class="class1">
    <thead>...<thead>
    <tbody>
        <tr id="1">
            <td class>cell1</td>
            <td class>cell2</td>
            <td class>cell3</td>
            <td class>cell4</td>
        </tr>
        <tr id="2">
            ....
        <\tr>
        ...

我需要遍历所有行并检查单元格编号3是否将“cell3”作为文本。 (对于初学者) 然后在香港专业教育学院发现之后,我需要继续检查3号单元格中不同字符串的行

我试过了:

string="cell3"
rows=browser.table.rows
rows.each {|tr| 
    if tr.td( :index =>2).text ==string
        puts " Found #{string}" 
        string="cellK"
    end
}

我正在循环中进行,因为我需要找到几个字符串。

但我得到了一个错误的错误:

 unable to locate element, using {:index=>2, :tag_name=>"td"}

有什么建议吗? 我如何获得td的文本? 为什么我不能通过索引找到td?

1 个答案:

答案 0 :(得分:4)

我猜这个问题是thead中的标题行。表头可能是这样的:

<thead>
    <tr id="0">
        <th class>heading1</th>
        <th class>heading2</th>
        <th class>heading3</th>
        <th class>heading4</th>
    </tr>
<thead>

请注意,有一个tr。因此table.rows将包含标题行。另请注意,它使用th代替td单元格。很可能在这里watir找不到索引为2的td,因为这一行根本没有tds。

假设这是问题,你有几个解决方案。

解决方案1 ​​ - 使用单元格生成th和td等效

在循环内部,使用cell代替td

rows.each {|tr| 
    if tr.cell( :index =>2).text == string    #Note the change here
        puts " Found #{string}" 
        string="cellK"
    end
}

Table#cell匹配tdth个单元格。这意味着cell(:index, 2)将匹配行中的第3个tdth。当watir检查标题行时,它现在将找到一个值。

解决方案2 - 忽略thead

获取要检查的行时,将rows集合限制为仅包含tbody中的行:

rows = browser.table.tbody.rows

然后会忽略引起问题的thead中的riws。