根据邻域单元格内容获取table个单元格内容

Get table cell content based on content of cell in neighbourhood

我有一个 table 结构如下:

<table class="table_class">
    <tr>
        <td>Label A</td>
        <td>Value A</td>
        <td>Label B</td>
        <td><div>Value B<a href="/some/href">Change</a></div></td>
    </tr>
    <tr>
        <td>Label C</td>
        <td><div><a href="/another/href">Value C</a></div></td>
        <td>Label D</td>
        <td><div><span><a href="/more/href"><span><img src="image/source.jpg"<img src="another/image.gif"></span></a><a href="even/more/href">Value D</a></span>&nbsp;<a href="/href">Change</a></div></td>
    </tr>
</table>

我想获取值("Value A"、"Value B"、...),但包含这些值的 table 单元格的唯一唯一标识符是table 个留给他们的单元格("Label A"、"Label B"、...)。

知道如何在 PageObject 中正确处理这个问题吗?

提前致谢, 克里斯蒂安

您可以使用带有 following-sibling 轴的 XPath 来查找相邻单元格的值。

例如,下面的页面对象有一个方法可以根据文本找到标签单元格。从那里,导航到下一个 td 元素,它应该是关联值。

class MyPage
  include PageObject

  def value_of(label)
    # Find the table
    table = table_element(class: 'table_class')

    # Find the cell containing the desired label
    label_cell = cell_element(text: label)

    # Get the next cell, which will be the value
    value_cell = label_cell.cell_element(xpath: './following-sibling::td[1]')
    value_cell.text
  end
end

page = MyPage.new(browser)
p page.value_of('Label A')
#=> "Value A"
p page.value_of('Label B')
#=> "Value BChange"

根据您的目标,您还可以重构它以使用访问器方法。这将允许您拥有返回值单元格、其文本、检查其存在等的方法:

class MyPage
  include PageObject

  cell(:value_a) { value_of('Label A') }
  cell(:value_b) { value_of('Label B') }

  def value_of(label)
    table = table_element(class: 'table_class')
    label_cell = cell_element(text: label)
    value_cell = label_cell.cell_element(xpath: './following-sibling::td[1]')
    value_cell
  end
end

page = MyPage.new(browser)
p page.value_a
#=> "Value A"
p page.value_a?
#=> true