3

I would like to check if the page has a specific text. Best if I could check out a few texts right away.

For example, if there are "client", "customer", "order"

Here is the HTML code.

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

After checking this I would use if condition as in here. This is my attempt to do this, but this is not the best option. Besides I can not check more words, I tried with || only.

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

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

Besides, is it possible to throw a whole list of words in large numbers to check if they exist?

Mohsin Awan
  • 1,176
  • 2
  • 12
  • 29
serengeti
  • 117
  • 2
  • 15

2 Answers2

2
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 Test if a string contains any of the strings from an array

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

driver.findElement(By.cssSelector("div.findText > span")).getText();
Cavan Page
  • 525
  • 2
  • 12
  • Thanks for reply. I'm currently testing this approach. Looks like its working. But, it is possible to do the same while not using .getPageSource? Like using this HTML code that i posted. – serengeti Jul 20 '17 at 19:24
  • 1
    yeah you could do something like this for example (see updated post for better formatting) driver.findElement(By.cssSelector("div.findText > span")).getText() – Cavan Page Jul 20 '17 at 19:31
2

Take 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 the .parallelStream() instead.