兄弟不是元素时xpath如何获取文本 [英] xpath how to get text when the brother is not an element

查看:68
本文介绍了兄弟不是元素时xpath如何获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经有过这种形式;

<li>
    <span>name:</span>
    <p>Seca </p>
</li>

我使用这个 xpath 来获取 seca:

and I was using this xpath to get the seca:

ul/li/span[normalize-space(text())='name:']/following-sibling::p[1]/text())

一切都很好.

现在我没有 p 标签.所以我只有这个:

Now i don't have the p tag. so I just have this:

<li>
    <span>name:</span>
    Seca
</li>

我应该对我的代码做哪些修改才能现在获得 seca?

what edit should I do to my code to get the seca now please?

推荐答案

现在,Seca"只是 li 元素的另一个子元素 - 因此是 span<的后续兄弟元素/code> 元素.使用

Now, "Seca" is just another child of the li element - and thus a following sibling of the span element. Using

//ul/li/span[normalize-space(text())='name:']/following-sibling::text()

给你

[EMPTY LINE]
Seca
[EMPTY LINE]

您可能想要排除那些只有空格的行:

you might want to exclude those whitespace-only lines:

normalize-space(//ul/li/span[normalize-space(text())='name:']/following-sibling::text())

结果是

Seca

如果您的实际输入包含更多文本节点,请不要忘记将 [1] 添加到表达式中.

If your actual input includes more text nodes, do not forget to add [1]to the expression.

请注意,如果实际上没有理由对 span 的文本内容进行规范化并且仅考虑其直接子文本节点,则表达式可能会容易得多:

Note that the expression could be a lot easier if there is actually no reason to normalize the text content of span and to only consider its immediate child text nodes:

//ul/li[span='name:']/text()[2]

这篇关于兄弟不是元素时xpath如何获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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