Mark Mayo
Mark Mayo

Reputation: 12615

Getting the text after a label with Selenium WebDriver

I've found other questions that look for label text, but what I'm after is the text after a label.

So for example, I have a section of code:

<p>
<label>My awesome name:</label>
"Mark Mayo"
</p>

My understanding is that if I wanted the label, I could use an XPath query with something like:

//label[text()='My awesome name:']

to see if the label exists, but am unsure how to access plain text that isn't inside the label, but after it instead.

Suggestions?

Upvotes: 2

Views: 2690

Answers (1)

Timo T&#252;rschmann
Timo T&#252;rschmann

Reputation: 4696

Something like (I use Java syntax)

public String getNodeTextContent(WebElement node) {
    String nodeContent = node.getAttribute("textContent");

    List<WebElement> childs = node.findElements(By.xpath("*"));
    if (childs.size() == 0) {
        return allContent;
    }

    for (WebElement child : childs) {
        nodeContent = nodeContent.replace(child.getAttribute("textContent"), "");
    }

    return nodeContent;
}

it basically just removes the text contents of all direct children of the node from the node contents, which should leave only the real contents of the node.

Upvotes: 1

Related Questions