Java Selenium web automation example

Selenium Webdriver became a defacto standard for automating the web based test. Here we will see a very basic example of web automation using Selenuium framework.

Source code folder structure:


1. build.gradle
group 'com.firstfewlines'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'application'

sourceCompatibility = 1.8

mainClassName = 'com.firstfewlines.SeleniumSample'

repositories {

dependencies {
    compile('org.seleniumhq.selenium:selenium-java:3.4.0') {
        exclude group: 'org.seleniumhq.selenium', module: 'selenium-android-driver'
        exclude group: 'org.seleniumhq.selenium', module: 'selenium-iphone-driver'
        exclude group: 'org.seleniumhq.selenium', module: 'selenium-safari-driver'
        exclude group: 'org.webbitserver', module: 'webbit'
        exclude group: 'commons-codec', module: 'commons-codec'
        exclude group: 'cglib', module: 'cglib-nodep'

2. settings.gradle = 'selenium-example'


Here in the main method, we are initializing the ChromeDriver, opening the Google website and search for a text. Once the works done we should close the web browser using webDriver.quit() that is commented here so that we can see the result.

package com.firstfewlines;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


public class SeleniumSample {

    public static void main(String [] argv) throws Exception {

        WebDriver webDriver = new ChromeDriver();

        webDriver.navigate().to(new URL(""));

        WebDriverWait wait = new WebDriverWait(webDriver, 10000);
        wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.tagName("input"), 0));

        WebElement input = webDriver.findElement(By.cssSelector("#lst-ib"));

        input.sendKeys("Spark Java file upload example - First Few Lines");

//        webDriver.quit();

Download complete source code:

How to run the application?

  • Make sure you have latest version of Google Chrome installed.
  • Please download Selenium Webdriver for Google Chrome from
  • Place the chromedriver executable in a folder and add that folder to system path
  • Make sure you have latest version of Gradle installed and PATH is configured.
  • Download the attached source code zip file and unzip it to your local folder.
  • Go to the directory where you unzipped the file i.e. where the build.gradle is there
  • Run gradle clean run command
  • The application should start a Google Chrome and do the search automatically as stated in the code

Alternatively, you can use IntelliJ IDEa or Eclipse to import the Gradle project and run from there.


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus