Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text using selenium webdriver(xpath)

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.

like image 462
Hari Reddy Avatar asked May 30 '12 06:05

Hari Reddy


People also ask

How can I get XPath of text?

WebDriver driver; String getText = driver. findElement(By. xpath("your xpath")). getText();

How can you read a text in a web element using Selenium?

The Selenium WebDriver interface has predefined the getText() method, which helps retrieve the text for a specific web element. This method gets the visible, inner text (which is not hidden by CSS) of the web-element.

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.


1 Answers

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;
like image 126
Petr Janeček Avatar answered Oct 07 '22 09:10

Petr Janeček