3

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.

Andrzej Rehmann
  • 12,360
  • 7
  • 39
  • 38

4 Answers4

6

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

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • I guess the original question was a little unspecific. Hadn't got it either without the comments on your question... – Jens Erat May 21 '13 at 21:29
  • '//div[@class='A']/text()' is working but I get "text element" not "WebElement" and I get error in JUnit "text() is either invalid or does not result in a WebElement" – Andrzej Rehmann May 22 '13 at 06:07
0

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>
Andrzej Rehmann
  • 12,360
  • 7
  • 39
  • 38
0

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

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
Arun
  • 1
  • 1
0

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.

Ferdinando
  • 964
  • 1
  • 12
  • 23