1

I have this html :

<div class="b-datalist__item__subj">
hello
<span class="b-datalist__item__subj__snippet">hello world</span>
</div>

And I want to get only "hello" text, without "hello world". I write this code:

subject = this.driver.findElement(By.xpath("//div[@class = 'b-datalist__item__subj']")).getText();

But in console output I see "hellohello world". How can I fix it?

4
  • The <span> is inside the <div>. You'll want to look at the first child of the DIV to get that particular text node. Commented Jun 16, 2016 at 16:23
  • @ChrisSteele Can you fix my xpath, pls? Commented Jun 16, 2016 at 16:25
  • Something like //div[@class = 'b-datalist__item__subj']/text() will find the text node, I think. Commented Jun 16, 2016 at 16:59
  • @ChrisSteele It works for me. Thanks! Commented Jun 16, 2016 at 17:24

2 Answers 2

2

You will have to "subtract" the text inside the span from the complete text in the div. Something like:

String outsideText = driver.findElement(By.xpath("//div")).getText();
String insideText = driver.findElement(By.xpath("//span")).getText();
String yourText = outsideText.replace(insideText, "");

Adjust the XPaths as necessary for your situation.

Sign up to request clarification or add additional context in comments.

4 Comments

hmm, it's a very nice idea, but can I make it more simple with 1 xpath expression?
There is no support in XPath for what you are asking.
No problem. I should amend my comment above, in case anyone quotes me. :p XPath does have several substring* methods, most appropriate for your situation is probably zvon.org/comp/r/ref-XPath_2.html#Functions~substring-before . However, these are not available in Selenium; By.xpath() implements only methods that return entire XML nodes.
can use findElement(By.cssSelector("div") though.
-1

use the below as xpath:

//div[text()='hello']

1 Comment

I can have diff values in this tag, not only hello

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.