How to check if some text data is displayed on a page

I would like to check if the page has specific text. It is best if I run several texts at once.

For example, if there is a "client", "client", "order"

Here is the HTML code.

<div class="findText"><span>Example text. Football.</span></div>
      

Run codeHide result


After checking this, I will use a condition like here. This is my attempt at doing this, but not the best option. Also, I can't check more words, I tried with || only.

 if(driver.getPageSource().contains("google"))  {

                driver.close();
                driver.switchTo().window(winHandleBefore);
                }

      

Also, is it possible to enumerate a whole list of words altogether to check if they exist?

+3


source to share


2 answers


if(stringContainsItemFromList(driver.getPageSource(), new String[] {"google", "otherword"))
{
    driver.close();
    driver.switchTo().window(winHandleBefore);
}

 public static boolean stringContainsItemFromList(String inputStr, String[] items)
    {
        for(int i =0; i < items.length; i++)
        {
            if(inputStr.contains(items[i]))
            {
                return true;
            }
        }
        return false;
    }

      

stringContainsItemFromList () method from Check if string contains any string from array



If you just want to get the text of that element, you can use something like this instead of driver.getPageSource () ...

driver.findElement(By.cssSelector("div.findText > span")).getText();

      

+2


source


Have a look at Java 8 Streaming API

import java.util.Arrays;

public class Test {

    private static final String[] positiveWords = {"love", "kiss", "happy"};

    public static boolean containsPositiveWords(String enteredText, String[] positiveWords) {
        return Arrays.stream(positiveWords).parallel().anyMatch(enteredText::contains);
    }

    public static void main(String[] args) {
        String enteredText1 = " Yo I love the world!";
        String enteredText2 = "I like to code.";
        System.out.println(containsPositiveWords(enteredText1, positiveWords));
        System.out.println(containsPositiveWords(enteredText2, positiveWords));
    }
}

      

Output:



true
false

      

You can also use ArrayList by using .parallelStream () instead.

+2


source







All Articles