Dale Dale - 2 months ago 14
Java Question

how to use selenium get Text from an element not including it's sub-element

HTML

<div id='one'>
<button id='two'>i am button</button>
<button id='three'>i am button</button>
i am div
</div>


Code

driver.findElement(By.id('one')).getText();

Answer

I've seen this question pop up a few times in the last maybe year or so and I've wanted to try writing this function... so here you go. It takes the parent element and removes each child's textContent until what remains is the textNode. I've tested this on your HTML and it works.

/**
 * Takes a parent element and strips out the textContent of all child elements and returns textNode content only
 * 
 * @param e
 *            the parent element
 * @return the text from the child textNodes
 */
public static String getTextNode(WebElement e)
{
    String text = e.getText().trim();
    List<WebElement> children = e.findElements(By.xpath("./*"));
    for (WebElement child : children)
    {
        text = text.replaceFirst(child.getText(), "").trim();
    }
    return text;
}

and you call it

System.out.println(getTextNode(driver.findElement(By.id("one"))));