Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Selenium get text from an element not including its sub-elements

Tags:

java

selenium

HTML

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

Code

driver.findElement(By.id('one')).getText();
like image 834
Dale Avatar asked Sep 28 '16 07:09

Dale


1 Answers

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"))));
like image 106
JeffC Avatar answered Oct 04 '22 13:10

JeffC