Reading text using selenium webdriver(xpath)

14,419

I don't know about any way to do this in Selenium, so there's my JS solution. The idea is to get all children of the element (including the text nodes) and then select only the text nodes. You might need to add some .trim() (or JS equivalent) calls to get rid of unneeded spaces.

The whole code:

WebElement elem = driver.findElement(By.id("data"));
String text;
if (driver instanceof JavascriptExecutor) {
    text = ((JavascriptExecutor)driver).executeScript(
            "var nodes = arguments[0].childNodes;" +
            "var text = '';" +
            "for (var i = 0; i < nodes.length; i++) {" +
            "    if (nodes[i].nodeType == Node.TEXT_NODE) {" +
            "        text += nodes[i].textContent;" +
            "    }" +
            "}" +
            "return text;"
            , elem);
}

And just the JS for better readability.

var nodes = arguments[0].childNodes;
var text = '';
for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].nodeType == Node.TEXT_NODE) {
        text += nodes[i].textContent;
    }
}
return text;
Share:
14,419
Hari Reddy
Author by

Hari Reddy

Learning ...

Updated on June 18, 2022

Comments

  • Hari Reddy
    Hari Reddy about 2 years

    I'm using selenium to get some text on my webpage using xpath.

    The page tag structure is as follows -

    <span id="data" class="firefinder-match">
        Seat Height, Laden
      <sup>
         <a class="speckeyfootnote" rel="p7" href="#">7</a>
      </sup>
    </span>
    

    If I use the following code -

    driver.findElement(By.xpath("//span[@id='data']")).getText();
    

    I get the result = Seat Height, Laden 7

    But I want to avoid reading the text within the <sup> tags and get the result Seat Height, Laden

    Please let me know which xpath expression I can use to get my desired result.