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

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

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

What is the simplest 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?

Thanks.



Solution 1:[1]

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

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

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

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

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

Solution 2:[2]

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:

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

Solution 3:[3]

Locate using the parent tag and use .

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

div[@class='A']

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

Solution 4:[4]

You can also find it using:

//div[.='what next?']

So, it will return an item(div) which contains this value.

But keep in mind that it's a generic mapping, if you have multiple items with this value on the screen it won't be that accurate.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Andrzej Rehmann
Solution 3 Sulthan Allaudeen
Solution 4 Ferdinando