Get In Touch
401, Parijaat, Baner Pune 411021
[email protected]
Business Inquiries
[email protected]
Ph: +91 9595 280 870
Back

Selenium Web Automation Testing

Selenium is one of the most popular tools for web automation testing, known for its flexibility and ease of use. In this blog post, we’ll introduce Selenium, guide you through setting it up, and show you how to write your first test script.

What is Selenium?

Selenium is an open-source framework for automating web applications. It supports multiple programming languages, including Java, C#, Python, and Ruby, and works across various browsers like Chrome, Firefox, and Safari.

Selenium consists of several components:

  1. Selenium WebDriver: The core component for controlling the browser.
  2. Selenium IDE: A record-and-playback tool for creating quick test scripts.
  3. Selenium Grid: A tool for running tests across different machines and browsers in parallel.

Setting Up Selenium

Before you can start writing Selenium tests, you’ll need to set up your environment. For this example, we’ll use Java, but the setup process is similar for other languages.

Prerequisites:

  1. Java Development Kit (JDK): Download and install the JDK from Oracle’s website.
  2. Eclipse IDE: Download and install Eclipse IDE from the official Eclipse website.
  3. Selenium WebDriver: Download the Selenium WebDriver from the official Selenium website.

Step-by-Step Setup:

  1. Install Java and Eclipse: Follow the installation instructions on the respective websites.
  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
    • Right-click your project in the Project Explorer and select Build Path > Add External Archives.
    • Right-click your project in the Project Explorer and select Build Path > Add External Archives.

Writing Your First Test Script

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 are correctly added to your project.
  • Check for any typos or syntax errors in your code.

Advanced Selenium Features

Handling Dynamic Web Elements with Explicit Waits

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

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.

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, which acts as the central point for managing test requests:
    java -jar selenium-server-standalone.jar -role hub
  3. Start the Nodes: To register nodes (machines that execute tests), use the following command:
    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: Break your test scripts into reusable methods and classes.

Use Explicit Waits: Avoid using hard-coded waits. Instead, use explicit waits to handle dynamic web elements.

Keep Tests Independent: Each test should be able to run independently of others.

Log and Report: Implement logging and reporting to keep track of test results and debugging information.

Conclusion

In this blog post, we introduced Selenium and demonstrated how to set up your environment and write a basic test script. We also explored advanced features like handling dynamic web elements, data-driven testing, and parallel test execution with Selenium Grid. Selenium’s flexibility and robust features make it an excellent choice for web automation testing.

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 write to [email protected].

Shubhashri Deshmukh
Shubhashri Deshmukh

Leave a Reply

Your email address will not be published. Required fields are marked *