Dale Dale - 1 year ago 125
Java Question

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


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



Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download