• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Jira Selenium Protractor Testing SDLC Agile Methodology

Java Selenium Tutorial & Testing Interview Questions

  • Home
  • Interview Questions
  • Java
  • Java Programs
  • Test Cases
  • Selenium
  • Manual Testing
  • Difference
  • Search
SoftwareTestingo » Selenium » Selenium Tutorial » Run First Java Selenium WebDriver Automation Script

Run First Java Selenium WebDriver Automation Script

Last Updated on: July 2, 2019 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Selenium prerequisites
  • First Selenium Program
  • How To Write Selenium Script For WebDriver Version Before GeckoDriver
  • Selenium Code Examples
  • Why GeckoDriver?
  • What Is GeckoDriver?
  • Steps To Follow For Using Selenium GeckoDriver
  • How to Run the Selenium Test With Setup System.setProperty?
  • Selenium WebDriver Script Example
  • Explanation of the Code
  • Logs Generated By GeckoDriver
  • How to Hide Selenium Firefox Logs With Selenium
  • How to disable Firefox Logs?
  • Code to Disable Firefox Logs?
  • Selenium Script Execution In Chrome Browser
  • What tool versions are we going to use for the Selenium ChromeDriver setup?
  • What and Why ChromeDriver?
  • How can you download Selenium ChromeDriver?
  • Code Snippet to Execute in Chrome Browser
  • Disable Chrome Info Bar Message Using ChromeOptions
  • How to Maximize the Chrome Browser Using Chrome options?

First Java Selenium WebDriver Automation Script: In this post, we are going to learn the Selenium WebDriver commands, which are used to launch the web browsers in detail along with other additional customization, which is required for launching for some browsers like – chrome and internet explorer. For writing scripts, we are going to use Eclipse editor for writing our test scripts.

We are going to start from a very basic selenium script, and from that, we are going to advanced scripts. So, let’s start our selenium automation testing and try to the meaning of each statement on that.

Selenium prerequisites

Before starting our automation test script, we have to take care of some of the prerequisites, which should be done to run our test automation script in the Eclipse IDE. Those are:

  • Download And Install Java
  • Setup Eclipse
  • Configure Selenium WebDriver Client
  • Configure Eclipse with Selenium WebDriver
  • Create New Project in Eclipse
  • Create a new package and class
  • Add Selenium Jars into the project
  • Browser

If you have not Setup above things, then no need to worry because we have written a complete process step by step, follow these steps and complete them.

First Selenium Program

After Setup, all the prerequisites, now we are are all set to run our first Java Selenium Automation program. So, let’s start to automate a simple scenario like open the firefox browser and launch google on that.

How To Write Selenium Script For WebDriver Version Before GeckoDriver

Before the release of GeckoDriver, In our automation script, there is no need for using the System.setProperty() statements. Up to Selenium WebDriver version 2.53 or before its straight forward where there no requirement of GeckoDriver or any other driver. you need to write the code to instantiate the WebDriver and open the firefox. you can find the automation script below:

Selenium Code Examples

package com.softwaretestingo.learnSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class LaunchFirefox_2_53 
{
   public static void main(String[] args) 
   {
      WebDriver driver = new FirefoxDriver();
      driver.get("https://www.softwaretestingo.com");
      driver.close();
   }

}

Note: If you run the above program with Selenium WebDriver version 3, then you will get the below exception. To Fix this type of exception, you need to use the Selenium version 3 with GeckoDriver.

Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
   at com.google.common.base.Preconditions.checkState(Preconditions.java:847)
   at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:134)
   at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:44)
   at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:167)
   at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:355)
   at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:190)
   at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:147)
   at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:125)
   at com.softwaretestingo.learnSelenium.LaunchFirefox_2_53.main(LaunchFirefox_2_53.java:11)

Why GeckoDriver?

Mozilla develops the Gecko browser engine as part of the Mozilla Firefox browser. It’s not only specific to only for Firefox browser, its an open-source browser engine so anyone can use this in their application. This helps in rendering web pages.

What Is GeckoDriver?

We Have to understand the very basic things like what is Gecko and GeckoDriver and why we are using in our selenium script? Gecko is a web browser engine which is used by the various application which is developed by Mozilla Foundation.

Up to Selenium 2.0, a firefox plugin is used to control the browser, but when the WebDriver is a W3C standard like HTML, JavaScript, and CSS. So after WebDriver defined with the W3C standard, Selenium WebDriver is not maintaining its versions of WebDrivers for different browsers. After that, Mozilla foundation started implements its WebDriver standard that’s called Marionette Driver or Gecko driver. Similarly, Microsoft also implementation for their Edge browser. So if you are going to use Mozilla Firefox version 46 or above, you need to use the GeckoDriver.

Steps To Follow For Using Selenium GeckoDriver

  • Download the GeckoDriver from the Official Mozilla Github page link and in the end of the page you can get different drivers for different environment, so make sure you download the right driver according to your machine environment ( Windows/ Linux or 32 /64 bit), as I am using Windows 10 -64 bit operating system I have download the Win64 Gecko Driver.
  • Set the System property for GeckoDriver “webdriver.gecko.driver” and path of the GeckoDriver exe file. It will look something like below
System.setProperty("webdriver.gecko.driver", "{path to geckodriver}\\geckodriver.exe");

To create a class on the name of FirstSelenium_pgm and copy the below code on that.

How to Run the Selenium Test With Setup System.setProperty?

You can run your script By click on the java file on the Package Explorer section, hover over “Run As” and select “Java Application” or you can try this way also Right Click on Eclipse code and Click Run As > Java Application.

Note: For Copy the Location of GeckoDriver exe file, you can use a shortcut like Shift+ Right Click On the Gecko Driver and Select Copy as Path.

Selenium WebDriver Script Example

package com.softwaretestingo.learnSelenium;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirstSelenium_pgm 
{
   public static void main(String[] args) 
   {
      //Creating a driver object referencing WebDriver interface
      WebDriver driver;

      //Setting webdriver.gecko.driver property
      System.setProperty("webdriver.gecko.driver", "F:\\Selenium\\util\\drivers\\geckodriver.exe");

      //Instantiating driver object and launching browser
      driver = new FirefoxDriver();
    
      //Using get() method to open a webpage
      driver.get("http://google.com");

      //Closing the browser
      driver.quit();

   }

}

Explanation of the Code

You can see two errors. To solve those errors, you need to import the following 2 packages

  • import org.openqa.selenium.WebDriver: It references the WebDriver interface, which is required to instantiate a new web browser.
  • import org.openqa.selenium.firefox.FirefoxDriver; References the FirefoxDriver class that is required instantiate a Firefox-specific driver on the browser instance instantiated using WebDriver interface.

Let’s understand the use of Statements

In Selenium, we have different WebDrivers for different browsers like for access firefox browser we have GeckoDriver, for chrome browser we have chromeDriver and Internet Explorer browser we have IEDriver. As in the above automation script, we are trying to launching in Firefox browser so let’s understand the below commands in details:

WebDriver driver = new FirefoxDriver();

In the above statement, WebDriver is an interface, and we are creating a reference variable of type WebDriver, which we are using for instantiated “FirefoxDriver” class.

If you don’t know, you can read our post on the interface, where we are trying to share in detail the interface in Java. Anyway, Interface is a contract, so whichever class implements those interfaces must have to provide the implementation of all those methods which are defined inside that interface as an interface have only abstract methods. That’s why you are not allowed to instantiate an object of the interface. If you try to create an object of interface like the below statement, then you will see a compilation like saying, “Cannot instantiate the type WebDriver.”

WebDriver driver = new WebDriver();

So, for instantiated driver object we need classes like FirefoxDriver or ChromeDriver classes which are implemented the WebDriver interface, because of this reason we are writing like:

WebDriver driver = new FirefoxDriver();

Then one more question may arise in your mind that we can create a direct object of FirefoxDriver or ChromeDriver class like below:

FirefoxDriver driver = new FirefoxDriver();

Then why we are not creating like that? For such a question, I can say we can create the object like the above statement. Still, we are creating a reference of WebDriver interface helps in multi-browser testing with the help of the same driver object, only we need to change the browser-specific driver. In Java, such concepts are called upcasting.

Logs Generated By GeckoDriver

1561911349846	mozrunner::runner	INFO	Running command: "C:\\Program Files\\Mozilla Firefox\\firefox.exe" "-marionette" "-foreground" "-no-remote" "-profile" "C:\\Users\\SOFTWA~1\\AppData\\Local\\Temp\\rust_mozprofile.6zjjklh5v9ZZ"
1561911350646	addons.webextension.screenshots@mozilla.org	WARN	Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: mozillaAddons
1561911350646	addons.webextension.screenshots@mozilla.org	WARN	Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: resource://pdf.js/
1561911350647	addons.webextension.screenshots@mozilla.org	WARN	Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: about:reader*
1561911354794	Marionette	INFO	Listening on port 57258
1561911355277	Marionette	WARN	TLS certificate errors will be ignored for this session
Jun 30, 2019 9:45:55 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1561911370495	Marionette	INFO	Stopped listening on port 57258
[Child 12440, Chrome_ChildThread] WARNING: pipe error: 109: file z:/task_1560988636/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc, line 341
[Child 12440, Chrome_ChildThread] WARNING: pipe error: 109: file z:/task_1560988636/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc, line 341
[Parent 10188, Gecko_IOThread] WARNING: pipe error: 109: file z:/task_1560988636/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc, line 341
[Child 4124, Chrome_ChildThread] WARNING: pipe error: 109: file z:/task_1560988636/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc, line 341
[Child 4124, Chrome_ChildThread] WARNING: pipe error:
###!!! [Child][RunMessage] Error: Channel closing: too late to send/recv, messages will be lost

[GPU 844, Chrome_ChildThread] 
###!!! [Child][MessageChannel::SendAndWait] Error: Channel error: cannot send/recv

How to Hide Selenium Firefox Logs With Selenium

As you can say that when we are trying to run our above program, there are lots of logs are generated in the Eclipse console area. These are very low-level logs, which makes you a little bit confused when you have set up your logs in the script.

How to disable Firefox Logs?

In our script, we are not going to Delete the logs of GeckoDriver/Marionette logs. We are only adding few lines of code, which helps us redirect this GeckoDriver/Marionette browser level logs into a text file so that our console area looks clean, and it will show only what the logs we want to see.

Code to Disable Firefox Logs?

If you see the below code there we have created another property where we have put the log file location so that that will redirect the logs into that text file, and the codes look like below:

System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"C:\\temp\\logs.txt");

And the complete code looks something like this:

package com.softwaretestingo.learnSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Seleniumpgm_withoutlogs 
{
   public static void main(String[] args) 
   {
      //Creating a driver object referencing WebDriver interface
      WebDriver driver;

      //Setting webdriver.gecko.driver property
      System.setProperty("webdriver.gecko.driver", "F:\\Selenium\\util\\drivers\\geckodriver.exe");
      System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
      System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"logs.txt");
      
      // If you want to Store the GeckoDriver Logs in the Temporary Folder
      //System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,System.getProperty("java.io.tmpdir")+"geckodriverlogs.txt");

      //Instantiating driver object and launching browser
      driver = new FirefoxDriver();
    
      //Using get() method to open a webpage
      driver.get("http://google.com");

      //Closing the browser
      driver.quit();

   }
}

Note: If you do not provide the complete log file path and only mention the log file path, then the log file will be stored inside your Eclipse project folder.

If you have used the below statement, then that will help you to store the log file in the temporary folder of windows. So that no need to worry about that log file.

System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,System.getProperty("java.io.tmpdir")+"geckodriverlogs.txt");

You can find the log file, by the below steps:

Note: Press Windows+r, then search with “%temp%” then search with the file name, then you will get the log file.

Log File
Log File

 

Selenium Script Execution In Chrome Browser

Our early post, we have seen how to run the selenium script to automate in the Firefox browser using GeckoDriver. Now we are going to learn how we can set up selenium ChromreDriver in multiple ways, and also we will see the automation script which can launch the Chrome browser using Selenium.

Note: This is part of the Selenium tutorial series, so please make sure you have installed the latest version of Selenium WebDriver to avoid the compatibility issue with the chrome browser.

What tool versions are we going to use for the Selenium ChromeDriver setup?

For the below script, we have used the below versions of different tools like Selenium, ChromeDriver, and Chrome Browser.

Selenium – version 3.141.59
Chrome Browser – Version 75.0.3770.100 (Official Build) (64-bit)
ChromeDriver – ChromeDriver 75.0.3770.90

What and Why ChromeDriver?

As we know that WebDriver is responsible for the launch and communicate with the browsers. So for communicating with Chrome Browser, we are using the ChromeDriver, which helps WebDriver to do the job in chrome. Or we can say that ChromeDriver is a standalone server that implements the WebDriver’s wire protocol for the chrome browser. So for that, we have written below lines of codes

WebDriver driver = new ChromeDriver();

How can you download Selenium ChromeDriver?

We recommend using the latest version of chrome browser and the latest version of ChromeDriver in your program. So let’s see how and from where you can download and set up for Selenium WebDriver in step by step:

  • You can download the latest version of the ChromeDriver using this link.
  • Click On the latest version ChromeDriver, and you can see we have marked the latest version, which is ChromeDriver 76.0.3809.25.
  • When you click on the link, it will redirect to another url from you can download the latest version of chrome driver also for different environments like mac, windows, and Linux.
  • As we are using a windows system, you need to download chromedriver_win32.zip, and those are using different environments they can download their respective versions.
  • Once you have completed the download process, you can unzip the downloaded zip file to retrieve the chromedriver.exe file.

With the above steps, we have completed the download ChromeDriver process, and now we can move the next phase, which is how to setup ChromeDriver for your project.

As we have used System.setProperty to mention the type of driver we are going to use and the location for the ChromeDriver. So let’s see how we can automate the Chrome browser using System.setProperty.

Code Snippet to Execute in Chrome Browser

package com.softwaretestingo.learnSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchChrome_Browser 
{
   public static void main(String[] args) 
   {
      System.setProperty("webdriver.chrome.driver", "F:\\Selenium\\util\\drivers\\chromedriver.exe");
      WebDriver driver=new ChromeDriver();
      driver.get("https://www.google.com");
      driver.close();
   }
}

When we have the run code, our codes fails, and we get an Exception Below:

Starting ChromeDriver 76.0.3809.25 (a0c95f440512e06df1c9c206f2d79cc20be18bb1-refs/branch-heads/3809@{#271}) on port 10741
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 76
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'DESKTOP-VPIA6P7', ip: '192.168.0.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_92'
Driver info: driver.version: ChromeDriver

As we have seen in the exception, it is mentioned that “Exception in thread “main” org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 76″, To Fix that we have to use the suitable version and we can do that by downgrade our chrome driver version. So I have download the other version ChromeDriver 75.0.3770.90. And after doing that changes, your script will run smoothly.

Disable Chrome Info Bar Message Using ChromeOptions

Chrome info Bar
Chrome info Bar

If you have noticed whenever we are running our script, it will launch a chrome browser along with it is showing an info bar with a message “Chrome is being controlled by automated test software.” So we can remove that message from the chrome browser using disable-info bars argument from ChromeOptions class. And the code looks something like below:

package com.softwaretestingo.learnSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class LaunchChrome_WithoutInfobar 
{
   public static void main(String[] args) throws InterruptedException 
   {
      System.setProperty("webdriver.chrome.driver", "F:\\Selenium\\util\\drivers\\chromedriver.exe");
      
      //For Disable Chrome Info Bar
      ChromeOptions option=new ChromeOptions();
      option.addArguments("disable-infobars");
      WebDriver driver=new ChromeDriver(option);
      driver.get("https://www.google.com");
      driver.close();
   }
}

If you run your script, then you will not see the Chrome info bar again in your browser.

How to Maximize the Chrome Browser Using Chrome options?

Its always a group approach of automation testing is open the browser with maximizing mode and a good to maximize the browser itself when you are launching the Chrome browser. We can do this by using ChromeOptions class, let’s know how can we do that. You can see the code below:

package com.softwaretestingo.learnSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class LaunchChrome_WithMaximize_Browser 
{
   public static void main(String[] args) throws InterruptedException 
   {
      System.setProperty("webdriver.chrome.driver", "F:\\Selenium\\util\\drivers\\chromedriver.exe");
      
      //For Disable Chrome Info Bar
      ChromeOptions option=new ChromeOptions();
      option.addArguments("disable-infobars");
      option.addArguments("--start-maximized");
      
      WebDriver driver=new ChromeDriver(option);
      driver.get("https://www.google.com");
      Thread.sleep(5000);
      driver.close();
   }
}

This way, you can do customization with these options and a few other settings you can learn from here.

 

    Filed Under: Selenium Tutorial

    Reader Interactions

    Comments

    1. Amol says

      December 19, 2019 at 8:51 PM

      Very Detailed and Clear instructions.. Thanks!!

      Reply
      • Softwaretestingo Admin says

        December 20, 2019 at 5:25 PM

        Thanks For such kind words

        Reply
    2. samson says

      April 27, 2020 at 5:44 AM

      Superb Explanation. I never came across this much of informaton in any selenium learning portal.

      Thanks and keep going. So Interested to Learn Selenium again from Scratch from Website.

      Reply
      • Softwaretestingo Editorial Board says

        April 29, 2020 at 1:08 PM

        We Glad its give you better understanding about selenium… i hope you spread this link with others also, so that your friends & colleges also got benifited from it

        Reply
    3. Vandana Dhiman says

      August 6, 2020 at 6:29 PM

      Amazing. It helped me doing a quick revision and I must say the content is updated and to the point. Thanks a lot for the efforts.
      I have started learning for job switch purpose and the content here is very much helping me in the same. I wont be looking any other site now. I am sure by just following this site I would really be able to get my work done.

      Reply
      • Softwaretestingo Editorial Board says

        August 6, 2020 at 8:17 PM

        Thanks For Such kind words and we glad that you like the content. As you have mentioned that you are planning to switch for new opportunity we suggest you to refer the Software Testing interview questions, where we have shared around 200+ companies real time interview questions

        Reply
    4. KKK says

      August 21, 2020 at 10:13 PM

      Really Impressed the way you have structured the every thing in clear in all the way to referrsh at one place

      Reply
      • Softwaretestingo Editorial Board says

        August 22, 2020 at 5:06 AM

        We Glad that you like this post

        Reply

    Leave a Reply Cancel reply

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

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Tutorials Important Links

    • Software Testing Jobs
    • Manual Testing Tutorial
    • Selenium Tutorial
    • Core Java Tutorial
    • TestNG Tutorial
    • Java Programs
    • Selenium Programs
    • Manual Test Cases
    • Interview Tips
    • Contact US
    • www.softwaretestingo.com

    Important Links

    • Software Testing Interview Questions
    • Agile Interview Questions
    • Manual Testing Interview Questions
    • Testing Interview Questions
    • Selenium Interview Questions
    • Selenium Real Time Interview Questions
    • Selenium WebDriver Interview Questions
    • Automation Framework Interview Questions
    • Appium Interview Questions
    • TestNG Interview Questions
    • Java Interview Questions
    • Core Java Interview Questions

    Categories

    Copyright © 2021 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy