Search code examples
seleniumwebdriver

Getting text from a node


I have a piece of HTML like this:

<a href="/something">
     Title
    <span>Author</span>
</a>

I got a WebElement that matches this HTML. How can I extract only "Title" from it? Method .getText() returns "Title\nAuthor"...


Solution

  • You can't do this in the WebDriver API, you have to do it in your code. For example:

    var textOfA = theAElement.getText();
    var textOfSpan = theSpanElement.getText();
    var text = textOfA.substr(0, textOfA.length - textOfSpan.length).trim('\n');
    

    Note that the trailing newline is actually part of the text of the <a> element, so if you don't want it, you need to strip it.