Reading text using selenium webdriver(xpath)

0
0

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.

  • You must to post comments
0
0

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;
  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website