使用 XPath 查询访问文本时遇到问题

Trouble accessing a text with XPath query

我有这个 html 片段

<div id="overview">
    <strong>some text</strong>
    <br/>
    some other text
    <strong>more text</strong>
    TEXT I NEED IS HERE
    <div id="sub">...</div>
</div>

如何获取我要查找的文本(显示为大写)?

我试过了,我收到一条错误消息,提示无法定位该元素。

"//div[@id='overview']/strong[position()=2]/following-sibling"

我试过了,我得到了 id=sub 的 div,但不是文本(正确)

"//div[@id='overview']/*[preceding-sibling::strong[position()=2]]"

除了用概述的内容进行一些字符串匹配或正则表达式之外,还有什么方法可以获取文本吗?

谢谢。

如果您总是想要 <div id="sub"> 之前的文本,那么您可以尝试

//div[@id='sub']/preceding-sibling::text()[1]

这将为您提供 </strong> 和开头 <div ... 之间的所有内容,即大写文本及其前导和尾随换行符和空格。

following-siblingaxis,您仍然需要指定实际节点(在您的示例中,XPath 处理器正在搜索名为 following-sibling 的元素)。您使用 ::.

将轴与节点分开

试试这个:

//div[@id='overview']/strong[position()=2]/following-sibling::text()[1]

这指定了 div 中第二个 strong 之后的第一个文本节点。