Xpath select 元素基于 2 个子元素条件

Xpath select element based on 2 child element conditions

这里是 html 代码:

<table>
<tr class="WhiteRow">
    <td align="center">
        <input id="SelectedDelivery1" type="checkbox" onclick="HandleClick(this.name,this.checked,"")" value="Y" name="SelectedDelivery1">
    </td>
    <td valign="top">
        <span></span>
        <span class="bold">Instrument Search</span>
        <br>
        abc (TRANSFER)
    </td>
    <td align="center">5 minutes</td>
    <td class="noborder" align="right">
    <td class="noborder" align="right">
    <td class="noborder" align="right">
    <td class="noborder" align="right">
</tr>
<tr>
    <td align="center">
        <input id="SelectedDelivery2" type="checkbox" onclick="HandleClick(this.name,this.checked,"")" value="Y" name="SelectedDelivery1">
    </td>
    <td valign="top">
        <span></span>
        <span class="bold">Instrument Search</span>
        <br>
        abc (CAVEAT)
    </td>
    ...
</tr>
</table>

我想定位包含 <span class="bold">Instrument Search</span>abc (TRANSFER)<tr>。 tr 可能不是 table.

中的第一个元素

到目前为止我试过了

//td/span[text()="Instrument Search"]/ancestor::tr

只满足其中一个条件,满足selector的tr有几个

你能告诉我如何定位他们吗

我在浏览语法后找到了自己的答案。 如果有其他更好的方法请告诉我

//td/span[text()="Instrument Search"]/ancestor::td/text()[contains(., "TRANSFER")]/ancestor::tr

使用以下 XPath 表达式:

//tr[contains(., 'abc (TRANSFER)') and contains(td/span[@class = 'bold'], 'Instrument Search')]

如果可能,您应该始终使用单向表达式,因为像 ancestor:: 这样的 "backwards" 轴可能是一个代价高昂的举动。这是优于您已经找到的解决方案的优势。

如果 span[@class = 'bold'] 不能包含除 "Instrument Search" 以外的任何内容,您应该将上面的表达式修改为:

//tr[contains(., 'abc (TRANSFER)') and td/span[@class = 'bold'] = 'Instrument Search']

"abc (TRANSFER)"的位置仍然不是很精确,如果在某个地方需要它(例如总是在td元素内)你必须进一步限制上面的内容。


编辑 回复您的评论:

abc (TRANSFER) is inside td tag, it's just a text field

然后使用

//tr[contains(td, 'abc (TRANSFER)') and td/span[@class = 'bold'] = 'Instrument Search']