xpath:查找不同行中具有相同位置的表格单元格

eld*_*111 7 html xpath selenium-webdriver

我正在解析包含这样的结构的网页:

<tr>
    <td>Label 1</td>
    <td>Label 2</td>
    <td>Label 3</td>
    <td>Something else</td>
<\tr>
<tr>
    <td>Item 1</td>
    <td>Item 2</td>
    <td>Item 3</td>
<\tr>
Run Code Online (Sandbox Code Playgroud)

我需要做的是根据它的标签选择一个项目,所以我的想法是如果标签位于其行的第3个标签中,我可以抓住下一行中的第3个标签来查找该项目.我无法想出以这种方式使用position()函数的方法,也许xpath(1.0)无法处理这种类型的过滤.

到目前为止,我最好的尝试是://td[ancestor::tr[1]/preceding-sibling::tr[1]/td[position()]].我希望position()函数可以获取<td>xpath开头的位置,因为xpath的其余部分是该节点的过滤器.

我正在努力做甚么可能吗?

kjh*_*hes 6

你走在正确的轨道上 - 是的,你可以position()随身携带count().

要选择Item 2给定的文字Label 2:

//td[. = 'Label 2']/../following-sibling::tr/td[position() = count(//td[. = 'Label 2']/preceding-sibling::td)+1]/text()
Run Code Online (Sandbox Code Playgroud)

说明: 选择第n个单元格,其中n由在前一行中具有所需标签的单元格之前存在的兄弟单元格的数量给出.实际上,使用该count()函数确定标签行中的位置,然后通过匹配它来选择下一行中相应的单元格position().