0

I need to get text value as indicated below:

<!DOCTYPE html>

    <html lang="en">
        <head>
        </head>
        <body>
            <b>Some Text I can find using xPath</b>
            <hr>
            **TEXT I WOULD LIKE TO FIND THAT IS BEING ADDED DYNAMICALLY - it will be different number every time page loads**
            <hr>
            **some other text dynamically added**
        </body>
    </html>

I tried by using

driver.findElement(By.xpath("/html/body/text()[1]"));

with no luck.

guda
  • 13
  • 3

1 Answers1

0

It's not straight forward due to the WebDriver not handling anything but element nodes. I opened a while ago two issues: one against the WebDriver and another one against the W3C WebDriver specification. (vote for them if, it helps showing a need of the user base).

Meanwhile, as a (painful) workaround, you will need to rely on JavascriptExecutor capabilities of your WebDriver. An example (in another context, thus will have to be adapted to your specifics), in one of my older answers.

Adapted to your case, with the note it may contain bugs cause by typos (I haven't checked it):

WebElement contextNode=driver.findElement(By.xpath("/html/body"));
if(driver instanceof JavascriptExecutor) {
  String jswalker=
      "var tw = document.createTreeWalker("
     +   "arguments[0],"
     +   "NodeFilter.SHOW_TEXT,"
     +   "{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT;} },"
     +    "false"
     + ");"
     + "var ret=null;"
     // skip over the number of text nodes indicated by the arguments[1]
     + "var skip;"
     + "for(skip=0; tw.nextNode() && skip<arguments[1]; skip++);"
     + "if(skip==arguments[1]) { " // found before tw.nextNode() ran out
     +   "ret=tw.currentNode.wholeText.trim();"
     + "}"
     + "return ret;"
  ;
  int textNodeIndex=3; // there will be empty text nodes before after <b>
  Object val=((JavascriptExecutor) driver).executeScript(
    jswalker, contextNode, textNodeIndex
  );
  String textThatINeed=(null!=val ? val.toString() : null);
}

Please let me know if/how it works.

Community
  • 1
  • 1
Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23
  • Thank you for your help. Closest to a solution for me is using – guda Oct 20 '16 at 00:50
  • 1
    Thank you for your comment, but the closest I got to a solution is this for me: value = driver.findElement(By.tagName("body")); value.getText().split("\n")[2]; - since dynamic value I need always apper on the same line in page (in my case third one). Thanks though, if no one presentes something more elegant I will use this one. – guda Oct 20 '16 at 00:52