Ways to verify if certain text information is present on the webpage

Is there a specific way to determine if certain texts are present on a webpage? It would be ideal to check multiple texts at once.

For instance, checking for "client", "customer", and "order" in the page content.

Below is an example of the HTML code snippet:

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

Once verification is completed, I plan to use an "if" condition like this one. However, my current method may not be the most efficient, as it only allows for single-word checks using logical OR (||) operators.

 if(driver.getPageSource().contains("google"))  {
   driver.close();
   driver.switchTo().window(winHandleBefore);
}

Additionally, is there a way to input a large list of words for validation purposes all at once?

Answer №1

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

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

checkIfStringContainsWord() method from Test if a string contains any of the strings from an array

If you prefer to extract just the text of that element, consider using this alternative approach instead of calling driver.getPageSource()...

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

Answer №2

Check out the 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 could also utilize ArrayList with .parallelStream() instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capturing Screenshots as Numpy Arrays Using Selenium WebDriver in Python

Can selenium webdriver capture a screenshot and transform it into a numpy array without saving it? I plan to use it with openCV. Please keep in mind that I'm looking for a solution that avoids saving the image separately before using it. ...

Utilizing Beautifulsoup to extract elements from Selenium

When utilizing BeautifulSoup with Selenium, I usually start by parsing the entire page using soup = BeautifulSoup(driver.page_source). But what if I only want to parse a specific element from Selenium in BeautifulSoup? If you try the following code snipp ...

Mastering communication between Android devices and handling complex data structures through socket programming

Recently, I've been exploring Android and I have a task at hand to establish a TCP socket connection and listen on a specific port. The client application will be sending me 2 images along with a related string. Instead of transmitting each piece of d ...

Using selenium to overcome access restrictions

While trying to automate website navigation using Selenium, encountering an issue stating: Access Denied. The server denies permission to access "http://tokopedia.com/". from selenium import webdriver from selenium.common.exceptions import NoSuch ...

Error encountered during execution of protractor tests in Azure DevOps due to absence of selenium server jar file

Attempting to execute a protractor test within an Azure DevOps pipeline is resulting in the following error message. It appears that the jar file path is referencing my local drive, even though the tests are being executed on the Azure DevOps server. Any s ...

Implementing wait functionality in Selenium using C# is essential for ensuring your tests

I've been tasked with writing Selenium C# code to log in to a website and check that the loading time is under 10 seconds. The challenge is that I'm not allowed to use any waiting functions, and since it's a login process, I don't have ...

Issues with tapping on iOS Simulator in Appium Sauce Lab are causing problems

Currently, I am trying to implement a functionality where tapping on an image in a webview triggers an action. However, despite tapping the image, it does not seem to register in Sauce Lab. IOSDriver driver = (IOSDriver) contextObj.getValue("driver"); ...

The automation script fails to launch on both Chrome and Firefox using Selenium and C# but interestingly, it works perfectly on Internet Explorer

Currently, I am testing a script in Visual Studio as a part of a project. The issue I am facing is that both Chrome and Firefox browsers are not running the script and eventually timeout. Surprisingly, Internet Explorer runs the script successfully without ...

Tips for Adjusting the Download Folder in Selenium with Python for Firefox

Hey there! I've hit a snag while trying to configure the Download folder in my project. My setup includes Mac, PyCharm CE, Selenium, Python, Behave, and Firefox as per project requirements. I attempted this setup from Python Selenium Firefox trouble ...

Jackson: A Guide to Extracting JSON Values

String url = "https://ko.wikipedia.org/w/api.php?action=query&format=json&list=search&srprop=sectiontitle&srlimit=1&srsearch=grand-theft-auto-v"; String result = restTemplate.getForObject(url, String.class); Map<String, String> ...

Finding Selenium SafariDriver Logs on Mac OSX

Has anyone had experience utilizing the Webdriver logs from Safaridriver on OSX? I am curious because despite configuring Safaridriver as shown below, I am unable to locate the logs in the specified directories such as '/User/${USER}', '/tmp ...

Encountering a NullPointerException when transferring inputs from scala.html to Controller as a form in Play framework (version 2.8.*) using

I am currently developing a Java web application using the Play Framework (2.8.19). In the process of creating a registration page, I encountered an issue with passing inputs from the registration page written in Scala to the controller class that is respo ...

I'm curious if anyone has successfully incorporated Selenium into their StoryTeller fixtures

Is there anyone who has successfully incorporated Selenium with StoryTeller fixtures? If so, what is the process for integrating them and how do they contribute to continuous integration? ...

Tips for validating the format of a date using Selenium 2

Looking for guidance on verifying email and date formats using Selenium WebDriver with TestNG. Can anyone help? ...

Can the creation of an Allure report be done within Python's unittest framework?

Is there a way to generate an allure report in python-unittest, similar to how it's done in Pytest? ...

Is there a way to execute automated selenium tests using TFS build 2015?

My NUnit selenium tests are integrated into Unit test and they work perfectly fine when run locally, but not on the TFS Server. After enabling code coverage, I noticed that "Module unittests.dll" was covering most of the code, while "Seleniumtest.exe" had ...

Tips on utilizing a document (such as an Excel sheet) from one task to another task within Jenkins

I have an Excel spreadsheet in the first job of Jenkins. Now I would like to transfer or duplicate it for use in my second job. How can I accomplish this task? ...

Extract keys from the string

Is there a better way to extract keys from a string? const {Builder, By, Key, until} = require('selenium-webdriver'); ... const obj = {val: 'Key.SPACE'} if(obj.val.startsWith('Key.'))obj.val = eval(obj.val); (...).sendKeys(obj ...

When using WebDriverIO in combination with VSC and JavaScript, any Xpath starting with //* is recognized as a comment

I'm in the process of creating a UI framework utilizing WebDriverIO within VSC. So far, everything is running smoothly, but I've encountered an issue where using XPath like the one below results in everything after //* being interpreted as a comm ...

What is the best method to ensure that Selenium WebDriver waits for an AJAX load to complete before proceeding with any

Is there a way to ensure that Selenium WebDriver waits for an Ajax load before proceeding with any activities? I am automating the process of filling out a form using my script, where I click on a button that opens a new form with some fields prepopulated ...