I am trying to create a Selenium getText() method that gets either the node text OR gets the node+child text of an element. By default, the Selenium behavior seems to use the Xpath .//string() method of getting text and including the text of immediate children. I want to take advantage of XPaths power to enable me to get the text in a more targeted way. My question is: am I misunderstanding this or is there a better way to accomplish 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;
}
Here is an HTML snippet:
<h5 class="class-name clearfix">Inner Text
<a class="info-link class-description" href="#">i</a>
</h5>
The problem is that I get the text Inner Texti when I use Selenium to do a text call like this:
driver.findElement(".//h5").getText();
My expectation was to retrieve the value Inner Text . By creating the method above, I hope to call it like so:
String text = elementHelper.getText(By.xpath(".//h5"),false);