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?

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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.
yeah you could do something like this for example (see updated post for better formatting) driver.findElement(By.cssSelector("div.findText > span")).getText()
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.