xpath:在不同行中查找具有相同位置的表单元格 [英] xpath: find table cell with same position in different row

查看:103
本文介绍了xpath:在不同行中查找具有相同位置的表单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am parsing a webpage that includes a structure like this:

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

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

What I need to do is select an item based on it's label, so my thought is if the label is in the 3rd tag in it's row, I can grab the 3rd tag in the next row to find the item. I can't figure out a way to use the position() function in this way, and maybe xpath (1.0) is unable to handle this type of filtering.

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

My best attempt so far is: //td[ancestor::tr[1]/preceding-sibling::tr[1]/td[position()]]. I was hoping the position() function would grab the position of the <td> at the beginning of the xpath, since the rest of the xpath is a filter for that node.

我想做的甚至是可能的吗?

Is what I'm trying to do even possible?

推荐答案

您在正确的轨道上-是的,您可以将position()count()一起使用.

You're on the right track -- yes, you can use position() along with count().

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

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

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

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().

这篇关于xpath:在不同行中查找具有相同位置的表单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆