I write the autotest, which checks a certain field on the site, for compliance. Everything works fine, but: I usually refer to an element through randomelement.getText(); pick up the text.

There was a problem that in my case, the text I need (not in the tag) is in a div , and besides this text, there are other lines enclosed in tags (all this is in the aforementioned div ).

As a result, does not get "1 pc." , and for example: "Your book: 1 pc. Book title."

Question: can I somehow try to fish only "1 pc."?

I check the text with - assertEquals(radndomElement.getText(), "1 шт.");

I use: Java , Selenium , TestNg .

    2 answers 2

    As an option, try:

    1. get a list of nested tags
    2. get text from each nested tag
    3. remove the contents of each nested tag from the main text.
    • Yes, a good option. But I will hold the question open a little, maybe someone else knows another method) - sank
    • It seems that they themselves are selenium'ovtsy and use - groups.google.com/forum/#!topic/webdriver/3mbMXA3sdlA (at the very end a loaded piece of code) - Mikita Berazouski
    • @MikitaBerazouski, yes indeed. - sank

    Generally looked at the link, they had this code:

     public static String geNodeText(WebElement element) { String text = element.getText(); for (WebElement child : element.findElements(By.xpath("./*"))) { text = text.replaceFirst(child.getText(), ""); } return text; } 

    The code works, but in my case it gives it in the form:

     1 строка 2 строка 3 строка 

    Made your own version:

     public static String geNodeTextSec(WebElement element,int startStringPoint,int endStringPoint) { String text = element.getAttribute("innerText").trim().replaceAll("\\n", ""); // Весь текст перегоняем в одну строку String newText = text.substring(startStringPoint,endStringPoint); // Выбираем нужный нам отрезок return newText; }