DEV Community

Cover image for Sample code to setup Selenium, chrome driver with a java project

Posted on

Sample code to setup Selenium, chrome driver with a java project

Slenium is popular open source project that consists of a range of tools and libraries. Here is the most basic example to get started selenium with a java project.

At the core of the selenium is webdriver.

It is a powerful API that drives a browser natively, just as a user would do.

Major components of webdriver are - selenium client library, JSON wire protocol over HTTP, browser drivers, and browsers.

To get started first, download webdriver version 96. Select the webdriver version as per the chrome browser version where the tests will be executed.

Get file and unzip it the project directory.

The project that I am using here is a java project created using gradle build.

The next step is to unzip and copy the driver the project directory.

unzip /tmp/ -d <PROJECT_DIR>/webdriver/v96/

Once the driver is ready, now it is time to write a sample program.

Make sure program should import the selenium related packages from org.openqa.selenium

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

public class SeleniumBasicExample { 
 final static String PROJECT_PATH = System.getProperty("user.dir");
  public void run() 
    throws Exception
      System.setProperty("", PROJECT_PATH + "/webdriver/v96/chromedriver");
      ChromeOptions chromeOptions = new ChromeOptions();

      WebDriver driver = new ChromeDriver(chromeOptions); 
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

      // set any url for test, here is an example with google
      if (driver.getPageSource().contains("I'm Feeling Lucky")) {
      } else {
Enter fullscreen mode Exit fullscreen mode

Here is the output of the above program -

selenium output

Download SeleniumBasicExample

Discussion (0)