Reading text using selenium webdriver (xpath)

I use selenium to get text on my webpage using xpath.

The structure of the page tag 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 in the <sup> tags and get the result Seat Height, Laden

Please let me know which xpath expression I can use to get the desired result.

+6
source share
1 answer

I do not know how to do this in Selenium, so there is my JS solution there. The idea is to get all the children of the element (including text nodes) and then select only text nodes. You may need to add a few .trim() calls (or the JS equivalent) to get rid of unnecessary spaces.

All 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 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; 
+7
source

Source: https://habr.com/ru/post/916976/


All Articles