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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.