Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

selenium - 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 Author"...

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('
');

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...