1

Below is the html code

<h2 id="xyz" class="test">
  <button class="restore 1" value="test2" title="hello"> Line1 </button>
  <button class="restore 2" value="test3" title="click"> Line2 </button>
  I need this text
</h2>

I need to extract the text "I need this text" from the above code.

I tried by the following ways but could not get the only line "I need this text:

1.) By.xpath("//h2[@id='xyz']").gettext(); getting error saying InvalidSelectorError: The result of the xpath expression "//h2[@id='xyz']/following-sibling::text()" is: [object Text]. It should be an element.

2.) By.xpath("//h2[@id='xyz']").getattribute(innerText); By this selector i am getting the output as line1,line2 & I need this text

My expected output should only be "I need this text"

Automation Engr
  • 444
  • 2
  • 4
  • 26

2 Answers2

3

The Selenium API doesn't support text nodes. If you wish to only get the text from the nodes, then use an helper function with some JavaScript:

WebElement element = driver.findElement(By.cssSelector("#xyz"));
String text = getNodesText(element);
public static String getNodesText(WebElement element) {
    String SCRIPT = 
     "for(var arr = [], e = arguments[0].firstChild; e; e = e.nextSibling) " +
     "  if(e.nodeType === 3) arr.push(e.nodeValue);                        " +
     "return arr.join('').replace(/ +/g, ' ').trim();                     " ;

    WebDriver driver = ((RemoteWebElement)element).getWrappedDriver();
    return  (String)((JavascriptExecutor)driver).executeScript(SCRIPT, element);
}
Florent B.
  • 41,537
  • 7
  • 86
  • 101
1

You're running the getText() method on a By. you need to run it on a WebElement:

WebElement h2 = driver.findElement(By.xpath("//h2[@id='xyz']"));
String wantedText = h2.getText();

Better of, use the ID directly:

WebElement h2 = driver.findElement(By.id("xyz"));

Edit: your second option that returns the hole text, e.g. Line1,line2 etc... Works. The html is written wrong since it has the buttons under the h2 tag... So your better option is to remove the text your getting from the buttons.

Moshisho
  • 2,781
  • 1
  • 23
  • 39
  • It didn't work .... No matter which type locator i use but if its used with gettext() method then it returns me a null value – Automation Engr Nov 21 '16 at 12:16
  • But that modification will be from HTML code side right ? is there any possible way through selenium that can work the trick out of this ? – Automation Engr Nov 21 '16 at 12:56
  • Yes, the change has to be in the html. Webdriver returns all of the text that h2 has, including the one under the button. Simply use String replace or something.. See here http://stackoverflow.com/questions/7775364/how-can-i-remove-a-substring-from-a-given-string – Moshisho Nov 21 '16 at 13:17