I have the following html:

<div class="dialog-components">
  <h2 class="dialog-title">
    <div class="help-link">
      <a href="http://google.com">Helps</a>
    Expected Result

And I want to getText: "Expected Result". But when I tried to:

String text = driver.findElement(By.cssSelector("div.dialog-components>h2")).getText();

The text is "Helps/nExpectedResult".

How can I get my expected text result?

  • There should be some tag with "Expected result" text , then only it can be get easily. like <p>Expected result</p> – Helping Hands Jun 24 '15 at 10:08
  • @HelpingHands: Yah, I see. But is it possible if we don't have some tags lik e<p> ? Thank you. – scorpion Jun 24 '15 at 10:35
  • 1
    You can split on the \n and grab the second line. The real problem here is poor development since they are just putting text willy nilly onto the page. – Paul Muir Jun 24 '15 at 11:04
  • @PaulDonny - I agree with your comment. – Helping Hands Jun 24 '15 at 11:06

You can get the nodevalue of the element using Javascript


Use executescript to execute JavaScript in the context of the currently selected frame or window

Below is an example in java

Don't forget to add return since you need to return the value to the caller

String expectedresult = (String)((JavascriptExecutor)driver).executeScript("return document.getElementsByClassName('dialog-components')[0].getElementsByTagName('h2')[0].childNodes[2].nodeValue;");

I tested the above code it was working fine

Hope this helps you...Kindly get back if you have any problems

| improve this answer | |
  • @scorpion oh that's gr8....happy to be of help – Vicky Jun 25 '15 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.