Creating a custom Selenium getText() method that can retrieve either the node text or the node plus child text of an element is my current challenge. The default behavior of Selenium appears to utilize the Xpath .//string() method which includes the text of immediate children. I aim to harness the power of XPaths for a more targeted approach to fetching text. So, my question is: am I misinterpreting this or is there a more efficient way to achieve this?
public String getText(By locationOfText, boolean childText)
{
By locator = null;
if (childText)
{
locator = ByChained(locationOfText, By.xpath(".//string()"));
} else {
locator = ByChained(locationOfText, By.xpath(".//text()"));
}
JavascriptExecutor jse = (JavascriptExecutor)driver;
String elementText = jse.executeScript("document.evaluate(locator, document.body, null,
XPathResult.STRING_TYPE, null);");
return elementText;
}
Below is an HTML snippet:
<h5 class="class-name clearfix">Inner Text
<a class="info-link class-description" href="#">i</a>
</h5>
The issue arises when using Selenium to extract text like this:
driver.findElement(".//h5").getText();
Instead of only "Inner Text", it retrieves Inner Texti. This leads me to expect that by utilizing the above method, I can employ it in this manner:
String text = elementHelper.getText(By.xpath(".//h5"), false);