Selenium

How to Check if an Element Exists in Selenium

Selenium helps us to automate a varied range of scenarios on testing. It gives a good Return on Investment (ROI) for automating the regression test cases for a product to certify its quality.

At the time of creating automation scripts, we often encounter a situation where we need to verify the presence of an element on the web page. Today, we shall explore techniques to deal with this requirement using Selenium.

Illustration Scenario

Let us take a scenario to ascertain if the text — Selenium automates browsers. That’s it! — exists on the page:

Url: https://www.selenium.dev/

Approach 1: Explicit Wait Condition

The first approach is using the expected condition — presenceofElementLocated, which comes under the explicit wait concept in Selenium.

In explicit wait, the Selenium holds back for a specified time till a certain condition is met. Once the given time has passed, the following automation step gets executed. For our test scenario, the execution is paused until the element we are looking for has been located by Selenium:

Implementation using Approach 1
Let us have a Java file FirstAssign.java with the following code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class FirstAssign {
    public static void main(String[] a) {

        System.setProperty("webdriver.chrome.driver", "chromedriver");
        WebDriver brw = new ChromeDriver();
        brw.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        brw.get("https://www.selenium.dev/");
        String text = brw.findElement(By.tagName("h1")).getText();

        try {
            WebDriverWait wait = new WebDriverWait(brw, 5);
    Wait.until
(ExpectedConditions.presenceOfElementLocated
((By.tagName("h1"))));

            System.out.println("The searched text: " + text + " exists.");

               } catch (NoSuchElementException execption) {
            System.out.println
("The searched text: " + text + " does not exists.");
            execption.printStackTrace();
        }

        brw.quit();
    }

}

After completing the implementation, we need to save and run this Java file:

In the previous code, lines 1 to 7 are the Java imports needed for Selenium. Lines 9 and 10 describe the name of the class and static object declaration.

In line 12, we instruct the Selenium WebDriver to search for the Chrome driver executable file within the project directory.

In lines 13 to 15, we first create a Selenium WebDriver object and store it in the brw variable. Then, we have introduced an implicit wait for the WebDriver object for three seconds. Lastly, we are opening the https://www.selenium.dev/ application in the Chrome browser.

In line 16, we have identified the searched element with the tagname locator and then stored its text in a variable using the getText() method.

Lines 18 to 30 are used for try-catch block, having the implementation of explicit wait. In line 20, we have created an object. The WebDriverWait has the WebDriver object and the wait time of five seconds as arguments.

Line 22 has the until method. The WebDriver object will wait for five seconds to check if the element we are looking for exists or not (expected criteria).

Once the existence of the expected element is confirmed, we print the corresponding text in the console.

If the element is not found, we will get a NoSuchElementException exception, which is handled in the catch block (lines 26 to 30).

Finally, in line 32, we quit the browser session.

Output
On running the above code, we have obtained the text — The searched text: Selenium automates browsers. That’s it! — exists as an output. In this way, we have checked if the element we are looking for exists: 

Approach 2: With the Help of the getPageSource() Method

Another approach to verify if an element exists on a page is to use the getPageSource() method. It yields the page source code.

Implementation using Approach 2
Let us have a Java file SecondAssign.java with the following code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class SecondAssign {
    public static void main(String[] p) {

        System.setProperty("webdriver.chrome.driver", "chromedriver");
        WebDriver brw = new ChromeDriver();
        brw.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        brw.get("https://www.selenium.dev/");
        String text = brw.findElement(By.tagName("h1")).getText();

        if (brw.getPageSource()
.contains("Selenium automates browsers"))            
        {   System.out.println("The searched text: " + text + " exists.");
        } else
System.out.println
("The searched text: " + text + " does not   exists.");
        brw.quit();
    }

}

Post the implementation. We require to save and run this Java file:

In the above code, lines 1 to 4 are the Java imports needed for Selenium.

Lines 6 and 7 are the class name and static object declaration.

In line 9, we instruct the Selenium WebDriver to search for the Chrome driver executable file within the project directory.

In lines 10 to 12, we first create a Selenium WebDriver object and store it in the brw variable. Then, we have introduced an implicit wait for the WebDriver object for three seconds. Lastly, we are opening the https://www.selenium.dev/ application in the Chrome browser.

In line 13, we have located the searched element with the tagname locator. Then, it stored its text in a variable using the getText() method.

Lines 15 to 18 are used for an if-else block. We are verifying if the page source code returned by the getPageSource() method contains our expected element text.

Once the if condition returned true, we have printed the corresponding text in the console. Otherwise, the else block should be executed in lines 17 to 19.

At last, in line 19, we have closed the Chrome browser.

Output
We have the text executing the above code — The searched text: Selenium automates browsers. That’s it! — exists as output. With this technique, we have verified if the element we are looking for is available:

Conclusion

Thus, we have seen how to verify an element’s existence on a web page. First, we have used the explicit wait condition, and the second approach is based on the getPageSource() method. We should try to use the explicit wait technique since it reduces the execution time to a large extent. We hope you found this article helpful. Check out other Linux Hint articles for more tips and tutorials.

About the author

Debomita Bhattacharjee