Selenium - how to use getText () for partial text?

When I use the method getText()

in the following web class, I get the full text associated with it:

$('.row.session-panel.form-group .session-name [href]')[0]

<a href=​"/​10002267/​agenda/​session/​10020933">​"8:30am - 9:45am "<span>​Welcoming Notes​</span>​</a>​

      

If I use getText()

, I get the full text: "8:30 am - 9:45 am Welcoming Notes" . Is there a way to get only 8:30 AM - 9:45 AM without using Java special methods like substring()

?

-1


source to share


3 answers


It looks like exactly what you want is just text that is directly represented by the text nodes in your element a

. There is currently no method in Selenium that allows you to get the text of an element without getting the text of its children. You can do the following to extract text from the DOM directly.

String text = (String) ((JavascriptExecutor) driver).executeScript(
    "var parent = arguments[0]; "+
    "var child = parent.firstChild; "+
    "var ret = ""; "+
    "while(child) { "+
    "    if (child.nodeType === Node.TEXT_NODE) "+
    "        ret += child.textContent; "+
    "    child = child.nextSibling; "+
    "} "+
    "return ret;", a);

      

(It's been a while since I've coded in Java on a regular basis. This is converted from Python code. It might be better to represent it.)



The variable a

will be the anchor that you already found using one of Selenium's methods to find elements. If you need something more subtle (like remove spaces or any other extraneous character you don't need) and somehow can't do it on the Java side, you can add it to the code above on the JavaScript side. For example, you might have return ret.trim()

if you want to get rid of the start and end space.

I've used the method above in Chrome, Firefox and IE 10-11 with no problem. I don't see anything there that doesn't cover most of the basic DOM levels, so I expect it to work in any browser.

+1


source


I think you should be using substring ()



0


source


The DOM structure internally <a>

prevents you from using jQuery functions to manipulate the DOM easilly.

var fullTxt = $('.row.session-panel.form-group .session-name [href]')[0].getText()
var spanTxt = $('.row.session-panel.form-group .session-name [href] > span')[0].getText();
var finalTxt = fullTxt.replace(spanTxt,"")

      

If you cannot use substring()

, you cannot use split('"')[1]

as I suppose.

0


source







All Articles