java 什么 XPath 只选择 div 中的非标记文本。硒。爪哇

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16679442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:38:54  来源:igfitidea点击:

What XPath to select only non-taged text inside div. Selenium. Java

javahtmlxpathselenium

提问by Andrzej Rehmann

I want to select only the text "only this text" from the snipet below using XPath (in Java) but that text is randomand I don't know what is written there.

我只想使用 XPath(在 Java 中)从下面的 snipet 中选择文本“仅此文本”,但该文本是随机的,我不知道那里写的是什么。

 <div class="A">
    <input id="button" type="button">x</input>
    only this random text
 </div>

What is the simplest xpath?

什么是最简单的 xpath?

 //div[@class='A'][what next?]

I saw similar questions but answers are always too complicated and I would like to know the simplest way.

我看到了类似的问题,但答案总是太复杂,我想知道最简单的方法。

Also is there any other way, without using XPath (in Java),to get that text?

还有没有其他方法可以不使用 XPath(在 Java 中)来获取该文本?

Thanks.

谢谢。

回答by Jens Erat

You can select text nodes using the axis step text().

您可以使用轴步骤 选择文本节点text()

//div[@class='A']/text()

If you only want text nodes following the <input/>node, use this:

如果您只想要节点后面的文本<input/>节点,请使用以下命令:

//div[@class="A"]/input/following-sibling::text()

You can add arbitrary predicates to the <input/>element, too - like you did for the <div/>.

您也可以向<input/>元素添加任意谓词- 就像您为<div/>.

回答by Andrzej Rehmann

This works:

这有效:

//div[@class='A']/node()[not(self::input)]

But it returns text element, now WebElement
It seems there is no way to retrieve it as a WebElement because the text should be an element like this:

但是它返回的是文本元素,现在 WebElement
似乎没有办法将它作为 WebElement 检索,因为文本应该是这样的元素:

<div class="A">
    <input id="button" type="button">x</input>
    <text>only this random text</text>
 </div>

回答by Arun

Locate using the parenttag and use .

使用parent标签定位并使用 .

If there is not tag for the text inside the div tag.

如果 div 标签内的文本没有标签。

div[@class='A']

[contains(.,'only this random text')]

[包含(.,'只有这个随机文本')]