DEV Community

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

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 chromedriver_linux64.zip 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/chromedriver_linux64.zip -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;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

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

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

      // set any url for test, here is an example with google
      driver.get("https://google.com");
      Thread.sleep(1000);
      if (driver.getPageSource().contains("I'm Feeling Lucky")) {
       log("pass");  
      } else {
       log("fail");
      }
      driver.quit();
     }
}
Enter fullscreen mode Exit fullscreen mode

Here is the output of the above program -

selenium output

Download SeleniumBasicExample

Top comments (0)