Andrzej Rehmann
Andrzej Rehmann

Reputation: 13860

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.

Upvotes: 3

Views: 19144

Answers (4)

F&#225;bio Jesus
F&#225;bio Jesus

Reputation: 1

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.

Upvotes: 0

Jens Erat
Jens Erat

Reputation: 38722

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/>.

Upvotes: 6

Arun
Arun

Reputation: 1

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')]

Upvotes: 0

Andrzej Rehmann
Andrzej Rehmann

Reputation: 13860

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>

Upvotes: 0

Related Questions