7

我正在解析一个包含如下结构的网页:

<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>

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

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

我想要做的甚至可能吗?

4

1 回答 1

6

您走在正确的轨道上——是的,您可以position()count().

Item 2要选择给定的文本Label 2

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

Explanation: Select the nth cell where n is given by the number of sibling cells that exist before the cell that has the desired label in the previous row. In effect, use the count() function to determine position in the label row and then select the corresponding cell in the next row down by matching against its position().

于 2013-09-23T14:17:32.890 回答