Selenium Tutorial: Basics and Getting Started

Shahzeb Hoda - Sep 26 '22 - - Dev Community

Selenium is still the most influential and well-developed framework for web automation testing. Being one of the best automation frameworks with constantly evolving features, it is poised to lead the industry in all aspects as compared to other trending frameworks like Cypress, Puppeteer, Playwright, etc. Furthermore, using Selenium gives you the flexibility to use different programming languages like C#, Ruby, Perl, Java, Python, etc., and also accommodate other operating systems and web browsers for Selenium automation testing.

Selenium has come a long way from its inception to what it is available today. Selenium 4 is the latest and the greatest version of Selenium. It has come up with a lot of new features like new easier-to-use IDE and W3C compliance to make programming faster, easier, more efficient.

If you’re new to automation, then Selenium WebDriver is the best place to start. It provides everything that you need to kickstart your Selenium automation journey.

In this article, I will take you through the prerequisites and everything you need to know to get started with Selenium automation testing.

Major Building Blocks of Selenium

Selenium is a suite of tools that allow you to write automated tests in several programming languages against web applications. The Selenium project itself is hosted by the SeleniumHQ on GitHub and contains several Selenium open source projects. The suite includes the Selenium IDE, Selenium WebDriver, and Selenium Grid, each with a different approach to supporting browser automation.

Selenium IDE

Selenium IDE is a Firefox browser plugin that helps in creating automated web application testing. It has been developed by Selenium Project to provide an alternative to test scripts in other programming languages. Selenium IDE is different from its predecessors as it is a recording tool and not a code generator tool. This allows automation testers to generate scripts in any language supported by Selenium WebDriver API.

Testers can record their actions on the web application, then playback when required. Selenium IDE also generates detailed reports for the recorded tests, enabling testers to track the results of their tests and improve their test scripts.

Selenium WebDriver

Selenium WebDriver is a tool for automating testing web applications, which interacts directly with the browser without any intermediary, unlike Selenium RC (Remote Control) that depends on a server.

Some of the most important features of Selenium WebDriver includes:

  • Multiple Browser Support: Selenium WebDriver Supports multiple browsers such as Firefox, Opera, Safari, Internet Explorer and many more.

  • Speed: Selenium WebDriver performs much faster than Selenium RC.

  • Simple Commands: Selenium WebDriver uses simple commands that are easier to learn and implement.

Selenium Grid

Selenium Grid is a WebDriver management and distribution system. It consists of multiple nodes that communicate with each other to discover, manage, and distribute the tests across different environments.

The architecture of the Selenium Grid has been overhauled in the recent versions of Selenium 4. The new architecture facilitates three different modes of running the Grid — Standalone mode, Hub & Node mode, and fully-distributed mode. In addition, the Selenium Grid is majorly used to run tests in parallel. Parallel testing in Selenium can be executed in multiple browsers running in different OS.

If you are intrigued to know more about Selenium 4, you can further deep-dive into our blog on what is new in Selenium 4.

You can follow the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium testing, Cypress testing, CI/CD, and more.

Why Selenium for Automation Testing?

Since we are now familiar with what is Selenium let’s find out the various benefits of Selenium WebDriver, which make it stand from the crowd as a tool for Selenium automation testing:

  1. Open source: Since it is an open-source tool, it doesn’t require any licensing costs, giving it an upper hand over other test automation tools.

  2. Tool for every need: As Selenium has a suite of tools, it suits every need of the users. You can use various tools like Selenium WebDriver, Selenium Grid, and Selenium IDE for fulfilling your different needs.

  3. Supports all major programming languages: The major challenge that a tester or developer faces with an automation testing tool is language support. Since Selenium supports all major languages like JavaScript, Python, Java, Ruby, C#, Perl, .Net, and PHP, it is easier for testers to use.

As per Stack Overflow Developer Survey 2021, JavaScript is the most popular language among developers, followed by HTML/CSS, Python, etc.

Now execute your free automated web testing.

With many frameworks available for web automation testing, Selenium has grown from strength to strength and is now the go-to framework for web automation testing. However, in my opinion, Cypress vs Selenium comparison is still relevant in the field of web testing.

Selenium’s benefits are vast, and its drawbacks are few, but it’s essential to understand the framework’s drawbacks before incorporating it into your project.

  • Automation of Windows-based applications is not possible.

  • No in-built reporting mechanism.

  • Automating Captcha and QR code is not possible using Selenium WebDriver.

  • Selenium WebDriver does not support parallel testing.

Though Selenium comes with a lot of features to leverage, its true potential can be evaluated only over a cloud-based Selenium Grid. By the end of this tutorial on Selenium automation testing, you will be in a better position to run Selenium tests on local Selenium Grid and cloud Selenium Grid.

The cross-browser testing platforms of LambdaTest allow you to bring your website to the next level by providing a secure, scalable, and reliable online Selenium Grid that lets you run Selenium tests in parallel on 3,000+ online browsers and platforms configuration.

Here's an article that looks at what Regression testing is, its importance and types, and how to perform it.

Getting Started with Selenium Automation Testing

Selenium is a very popular automated testing framework for web applications. It is a browser-based automation framework that simulates user actions and automates the testing process. Selenium supports different browsers like Firefox, IE, Chrome, etc. Therefore, it can be used for both functional and non-functional testing. In addition, Selenium provides APIs and extensions in most programming languages to automate web applications using this framework.

To use Selenium in your automation project, you need to install the language bindings libraries for your programming language of choice and the Selenium WebDriver binaries for the browsers you want to test in.

In this section, we will discuss how you can get started with Selenium automation testing.

JAVA Installation

In this blog section on getting started with Selenium automation testing, we will see how to install and configure Selenium with Java as a programming language.

Java Development Kit (JDK) is a prerequisite for running Eclipse IDE on your computer. So you have to install and configure it before running the Eclipse IDE. JDK can be downloaded from the Java Downloads website.

  1. Download the JDK file that corresponds to the operating system of your computer.

  2. After installing Java, ensure you have set the environment variables. You can verify the success of the installation process by typing the following command in the command prompt
    java –version.
    This will generate information regarding the installed version of Java.

  1. After successfully installing and configuring the JDK on your computer, you must download Eclipse IDE from Eclipse IDE for the Java developers page. Select the correct version of the Eclipse-based on your OS, as shown in the below image.

  1. When you have downloaded the zip file, extract it to the location where you want to run the IDE. Then, you can run the program simply by double-clicking on the “eclipse.exe” file going through the Eclipse folder.

Installation of Selenium Library

Now we will download the Selenium Java Client Driver. This can be downloaded from the official Selenium website. Scroll downwards to the section Selenium Client and WeDriver Language Bindings. In our case, we will download the Java Binding. Start free testing, run your Selenium IDE tests on the cloud.

Installation of Browser Driver

Now, you need to download the browser drivers that will help you instantiate the browser. Below are the links to download the drivers for some major browsers:

  • GeckoDriver(Firefox)

  • InternetExplorerDriver

  • ChromeDriver

You can refer to the Browsers section in the Selenium Website to download drivers for more browsers. To launch any given browser, you must explicitly set the corresponding executable path. Once done, instantiate the driver instance and go ahead with the code execution. However, this can become a daunting task as for every version update, we have to follow the previous steps. This is where the “WebDriverManager” class in Selenium can help. You can download the driver’s binary file (or .exe files) using WebDriverManager for performing Selenium automation testing.

How to configure Selenium WebDriver with Eclipse

Follow these next steps to configure Selenium WebDriver with Eclipse.

Step 1: Double-click on the Eclipse icon.

Step 2: Create a new Workspace and click on Launch.

This will take you to the following interface.

Step 3: Go to File -> New -> Java Project to create a new project.

This will generate a pop-up window that requires you to fill in a few details, such as the Project name, save location, execution JRE, and layout option. You can name it a newproject, CrossBrowserTestingDemo or CBTDemo, or SeleniumDemo, and click on Finish.

Step 4: The new project will appear in the top left corner. The next step is to create a new package for the newly created project. To do this, right-click on the folder named ‘src’, select ‘New’, and then ‘Package’.

A new window will pop-up requiring you to fill in the package’s name. You can name it newpackage and click on ‘Finish’.

Step 5: Right-click on the newpackage to generate a Java class. Select New and click on Class.

This will generate a pop-up window that requires you to fill in the name of the class. Click on Finish when done. After creating the class, the Eclipse interface will appear as follows.

Step 6: The next step involves adding Selenium Jars to the newly created project. Right-click on the folder newproject and click on properties.

This will generate a pop-up window. On this window, click on Java Build Path and select Libraries.

Step 7: Click on Add External JARS to add Selenium JARS.

Step 8: Search for the folder containing the downloaded Selenium Client Driver. Then, click on the folder libs in the downloaded Selenium folder.

Highlight all the jar files and click open. Next, highlight the two jar files outside the lib folder and click open.

Step 9: Click on Apply and Close.

Step 10: Check whether the following two library folders appear on your Eclipse dashboard. If this is the case, you have successfully configured Selenium WebDriver with Eclipse.

Step 11: To add the TestNG Library in Eclipse, click Help->Eclipse Marketplace. In the search box, type “TestNG” and click Go. Next, click the “Install” button. In my system, it’s already installed. Once installed, the Eclipse may restart.

Step 11: To add the TestNG Library in Eclipse, click Help->Eclipse Marketplace. In the search box, type “TestNG” and click Go. Next, click the “Install” button. In my system, it’s already installed. Once installed, the Eclipse may restart.

However, another way to realize web automation testing using Java and Selenium is by using Maven. Maven is a project management tool that uses POM.xml. If you are not familiar with Maven, you can refer to the Selenium Maven tutorial for building and executing Selenium projects using Maven.

**In this article, look at what is Regression testing, its importance and types, and how to perform it. **

Sample Selenium Script for Web Automation

Now that I have touched upon web automation and installed all the necessary JAVA libraries, we shall get moving with writing our first Selenium script.

To demonstrate running of Selenium script for web automation, please consider the following problem statement:

  1. Launch Chrome browser.

  2. Open LambdaTest sign up page.

  3. Click on the Sign In button.

  4. Close the web browser.

Implementation:

package LambdaTest;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners({util.Listener.class})
class FirstTestScriptUsingWebDriver {
   public static WebDriver driver = null;
   @BeforeTest
   public void setUp() throws Exception {
       WebDriverManager.chromedriver().setup();
       driver=new ChromeDriver();
   }
   @Test
   public void firstTestCase() {
       try {
           System.out.println("Logging into Lambda Test Sign Up Page");
           driver.get("https://accounts.lambdatest.com/register");
           WebElement pageHeader= driver.findElement(By.xpath("//a[text()='Sign In']"));
           pageHeader.click();
           System.out.println("Clicked on the Sign In Button.");
       } catch (Exception e) {
       }
   }
   @AfterTest
   public void closeBrowser() {
       driver.close();
       System.out.println("The driver has been closed.");
   }
}
Enter fullscreen mode Exit fullscreen mode

Now, to import the necessary dependencies, please use the below pom.xml file.

File — pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>blogsCode</groupId>
  <artifactId>lambdaTest
  </artifactId>
  <version>0.0.1-SNAPSHOT</version>
 <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.1.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.4.0</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>5.0.3</version>
        </dependency>

    </dependencies>

</project>
Enter fullscreen mode Exit fullscreen mode

Now, for running the test case, use the below testng.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "[http://testng.org/testng-1.0.dtd](http://testng.org/testng-1.0.dtd)">
<suite  name="FirstTestScriptUsingWebDriverSuite">
   <test name="FirstTestScriptUsingWebDriver" >
       <classes>
           <class name="LambdaTest.FirstTestScriptUsingWebDriver" >
           </class>
       </classes>
   </test>
</suite>
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

BeforeTest annotation is a TestNG Annotation that helps execute a block of statements every time before any Test Method executes. So we can use this annotation to maintain a preset for every Test Method like launching browser, URL, and Login based on our requirement.

WebDriverManager is an open-source Java library. It helps carry out the driver exe path setup for all browsers like Chrome, Edge, and Firefox in a single line. Here WebDriverManager.ChromeDriver.setup initializes the latest Chrome browser installed in the system. However, even initializing the version of the browser also is possible.

Test is one of the more important TestNG Annotations, which define a standard Java method as TestMethod.

Try catch block helps to capture any runtime exception and helps to handle the way developers want to end that execution.

driver.get helps to launch the required URL. Here, the required element, the “Sign In” link, is identified using XPATH, a tag titled “Sign In”.

Each WebElement can be interacted with based on the element type, here as this element is a link, triggering click event.

system .out.println in Java helps to print messages in the console.

AfterTest is another TestNG Annotation that executes the statements after every Test Annotation method executes. We can write statements that help tear down the process, like closing files and browsers.

driver.close() method closes the current active browser launched by WebDriver. If there are multiple browsers, use driver.quit() to close all the sessions.

Run Selenium Test on Cloud Selenium Grid

As the complexity of our application increases, we need to make sure that we also have a parallel testing strategy. Parallel testing means running multiple tests simultaneously so that they can finish faster. The more distributed your tests are over multiple machines, the faster they finish.

The Selenium Grid makes parallel execution possible by sending commands to remote Web Browser instances from a hub server. The Grid enables you to test your website with different browsers on different operating systems. However, a more realistic scenario is where the Selenium test has to be run across different browser and OS combinations.

Instead of relying on local instances of Selenium, Selenium testing tools like LambdaTest offer a cloud Selenium Grid that lets you run parallel tests across 3000+ different browsers and operating systems. All you need is one line of code to instantiate the remote Selenium WebDriver instead of the local Selenium WebDriver.

To demonstrate the running of the Selenium script on LambdaTest, please consider the following problem statement:

  1. Launch Chrome browser on Windows 10

  2. Open LambdaTest sign up page.

  3. Click on the Sign In button.

  4. Close the web browser.

Implementation

package LambdaTest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

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

@Listeners({util.Listener.class})
class FirstTestScriptUsingSeleniumGrid {

  public String username = "YOUR USERNAME";
  public String accesskey = "YOUR ACCESSKEY";
  public static RemoteWebDriver driver = null;
  public String gridURL = "@hub.lambdatest.com/wd/hub";

  @BeforeTest
  public void setUp() throws Exception {
      DesiredCapabilities capabilities = new DesiredCapabilities();
      capabilities.setCapability("browserName", "chrome");
      capabilities.setCapability("version", "94.0");
      capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
      capabilities.setCapability("build", "FirstTestScript");
      capabilities.setCapability("name", "FirstTestScriptSample");
      try {
          driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
      } catch (MalformedURLException e) {
          System.out.println("Invalid grid URL");
      } catch (Exception e) {
          System.out.println(e.getMessage());
      }
  }

  @Test
  public void firstTestCase() {
      try {
          System.out.println("Logging into Lambda Test Sign Up Page");
          driver.get("https://accounts.lambdatest.com/register");
          WebElement pageHeader= driver.findElement(By.xpath("//a[text()='Sign In']"));
          pageHeader.click();
          System.out.println("Clicked on the Sign In Button.");
      } catch (Exception e) {

      }
   }

  @AfterTest
  public void closeBrowser() {
      driver.close();
      System.out.println("The driver has been closed.");
  }
}
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

The RemoteWebDriver class is used to execute test scripts through the RemoteWebDriver server on a remote machine.

To run the tests on the LambdaTest cloud Selenium Grid, you need to populate the values of the corresponding username and access key from the LambdaTest Profile Section.

To set the necessary capabilities of browser name, version, platform, etc., you can use the LambdaTest Desired Capabilities Generator.

The remaining implementation will remain unchanged, as the only implementation that has changed is migrating from a local Selenium Grid to a cloud Selenium Grid.

Execution

Log on to LambdaTest Automation Dashboard to check the status of the test execution on LambdaTest.

You can also navigate to the LambdaTest Analytics Dashboard to see the Test Overview, Test Trends, and Resource Utilization. The Test Overview provides the Test Case Health Snapshot for the tests that are consistently passing, consistently failing, etc. Whereas Test Summary shows the total number of tests passed, failed, completed, etc.

Conclusion

To summarize this article on Selenium automation testing, we have seen basic steps in setting up the requirements for running our simple test in Selenium. We also saw the basic code, step by step, to run a simple test case in Selenium.

You can also run Selenium tests on the cloud. There are a number of cloud testing tools like LambdaTest that let you access Selenium Grid without installing it locally. These cloud-based platforms eliminate the need to install and configure the Selenium Grid software. In addition, they make it easy to run tests in parallel and allow you to switch between multiple browsers.

I believe you are now all geared up to start on your Selenium automation journey.

Please keep us posted with your feedback and comments.

Happy Testing…!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .