Get In Touch701, Platinum 9, Pashan-Sus Road, Near Audi Showroom, Baner, Pune – 411045.
[email protected]
Business Inquiries
[email protected]
Ph: +91 9595 280 870
Back

Selenium Web Automation Testing

Selenium is one of the most widely used frameworks for web automation testing. In this guide, you’ll learn how to set up Selenium WebDriver, understand the main Selenium components, and write your first automation script. By the end, you’ll have a working project and a clear path to more advanced Selenium automation.

What is Selenium?

Selenium is an open-source framework for automating web applications. It supports multiple programming languages (Java, C#, Python, Ruby) and works across major browsers like Chrome, Firefox, and Safari. For most teams, how to set up Selenium WebDriver is the first step to building stable UI automation.

Selenium consists of several components:

    1. Selenium WebDriver: The core component for controlling the browser and interacting with web elements.
    2. Selenium IDE: A record-and-playback tool for creating quick scripts and prototypes.
    3. Selenium Grid: Runs tests across different machines and browsers in parallel to reduce execution time.

Setting Up Selenium WebDriver

Before you write tests, you need the environment ready. This section explains how to set up Selenium WebDriver using Java. The same general workflow applies to other languages as well.

Prerequisites:

    1. Java Development Kit (JDK): Install a JDK (for example, from Oracle or another trusted distributor).
    2. Eclipse IDE: Install Eclipse (or any Java IDE you prefer).
    3. Selenium WebDriver: Add Selenium libraries to your project (most teams do this via Maven/Gradle, but you can use .jar files too).

Step-by-Step Setup:

    1. Install Java and Eclipse: Complete installations and confirm Java is available on your system path.
    2. Create a New Project in Eclipse:
        • Open Eclipse and select File > New > Java Project.
        • Enter a project name and click Finish.
    3. Add Selenium Libraries to Your Project
        • If using .jar files: Right-click your project and select Build Path > Add External Archives, then select your Selenium WebDriver .jar files.
        • If using Maven/Gradle: Add Selenium dependencies to your build file and refresh the project (this is usually the cleanest approach for long-term maintenance).

Writing Your First Test Script

Now that you know how to set up Selenium WebDriver, let’s run a basic script that opens a browser, searches on Google, prints the title, and exits cleanly.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;

public class GoogleSearchTest {
    public static void main(String[] args) {
        // Set the path to the ChromeDriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Create a new instance of the Chrome driver
        WebDriver driver = new ChromeDriver();

        // Navigate to Google
        driver.get("https://www.google.com");

        // Find the search box using its name attribute
        WebElement searchBox = driver.findElement(By.name("q"));

        // Enter a search query
        searchBox.sendKeys("Selenium WebDriver");

        // Submit the search form
        searchBox.submit();

        // Print the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        // Close the browser
        driver.quit();
    }
}

To run your test script, right-click the file in Eclipse and select Run As > Java Application. The browser should open, navigate to Google, perform the search, and then close.

If you encounter issues, check the following:

    • Ensure the path to the ChromeDriver executable is correct.
    • Verify that the Selenium WebDriver .jar files (or Maven/Gradle dependencies) are correctly added.
    • Check for any typos or syntax errors in your code.

Advanced Selenium Features

Handling Dynamic Web Elements with Explicit Waits

Explicit waits are essential for stable automation. Even after you learn how to set up Selenium WebDriver, unreliable timing is one of the biggest causes of flaky tests. Explicit waits let Selenium wait for the right condition before interacting with an element.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class DynamicElementHandling {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement dynamicElement = wait.until(
                ExpectedConditions.elementToBeClickable(By.id("dynamicElement"))
        );

        dynamicElement.click();
        driver.quit();
    }
}

Data-Driven Testing with Excel

Data-driven tests help validate many inputs quickly. Once you’ve completed how to set up Selenium WebDriver, data-driven testing is a practical next step for expanding coverage without duplicating scripts.

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class DataDrivenTest {
    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        FileInputStream file = new FileInputStream(new File("path/to/testdata.xlsx"));
        Workbook workbook = new XSSFWorkbook(file);
        Sheet sheet = workbook.getSheetAt(0);

        for (Row row : sheet) {
            Cell cell = row.getCell(0);
            String searchQuery = cell.getStringCellValue();

            driver.get("https://www.google.com");
            WebElement searchBox = driver.findElement(By.name("q"));
            searchBox.sendKeys(searchQuery);
            searchBox.submit();

            System.out.println("Page title for query '" + searchQuery + "': " + driver.getTitle());
        }

        driver.quit();
        workbook.close();
        file.close();
    }
}

Running Tests in Parallel with Selenium Grid

Selenium Grid allows you to run tests across multiple browsers and machines in parallel, significantly reducing test execution time. For larger suites, Grid becomes especially useful after you’ve mastered how to set up Selenium WebDriver and established stable tests.

Setting Up Selenium Grid:

    1. Download Selenium Server: Download the Selenium Server standalone jar file from the Selenium website.
    2. Start the Hub: Run the following command to start the hub:
      java -jar selenium-server-standalone.jar -role hub
    3. Start the Nodes: Register nodes (machines that execute tests):
      java -jar selenium-server-standalone.jar -role node -hub http://localhost:4444/grid/register

After setting up the hub and nodes, Selenium Grid is ready to run your tests across different machines and browsers simultaneously.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.By;

import java.net.MalformedURLException;
import java.net.URL;

public class GridTest {
    public static void main(String[] args) throws MalformedURLException {
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);

        driver.get("https://www.google.com");
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("Selenium Grid");
        searchBox.submit();
        System.out.println("Page title is: " + driver.getTitle());

        driver.quit();
    }
}

Best Practices for Selenium Automation

Modularize Your Code: Create reusable methods and page objects to keep your suite maintainable.

Modularize Selenium tests using reusable classes and methods

Use Explicit Waits: Avoid hard-coded waits. Use explicit waits for stable element interactions.

Use explicit waits for dynamic web elements in Selenium

Keep Tests Independent: Each test should run independently to reduce cascading failures.

Keep Selenium tests independent for reliable execution

Log and Report: Add logging and reporting to speed up debugging and visibility.

Add logging and reporting for Selenium automation suites

Conclusion

In this blog post, we covered how to set up Selenium WebDriver, wrote a basic Selenium test script, and explored advanced concepts like explicit waits, data-driven testing, and parallel execution with Selenium Grid. Selenium remains a strong choice for web automation due to its flexibility, language support, and ecosystem.

For more details about such case studies, visit us at www.corecotechnologies.com. If you would like to convert this virtual conversation into a real collaboration, please contact us!

 

Shubhashri Deshmukh
Shubhashri Deshmukh