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. We are going to use Eclipse editor to write our test scripts.
We will start with a very basic selenium script, and from there, we will move on to advanced scripts. So, let’s start our selenium automation testing and try to understand 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 a New Project in Eclipse
- Create a new package and class
- Add Selenium Jars to the project.
- Browser
If you have not set up the above things, there is no need to worry because we have written a complete step-by-step process; follow these steps and complete them.
First Selenium Program
After setting up all the prerequisites, we are all set to run our first Java Selenium Automation program. So, let’s start automating a simple scenario like opening the Firefox browser and launching Google.
How To Write Selenium Script For WebDriver Version Before GeckoDriver
Before the release of GeckoDriver, In our automation script, there was no need to use the System.setProperty() statements. Up to Selenium WebDriver version 2.53 or before it’s straight, there is no requirement for GeckoDriver or any other driver. you need to write the code to instantiate the WebDriver and open 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("http://www.softwaretestingo.com"); driver.close(); } }
Note: If you run the above program with Selenium WebDriver version 3, you will get the exception below. 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 the Firefox browser but also an open-source browser engine so that anyone can use this in their application. This helps in rendering web pages.
What Is GeckoDriver?
We must understand basic things like what Gecko and GeckoDriver are and why we use them in our selenium script. Gecko is a web browser engine used by various applications and was developed by the 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 is defined with the W3C standard, Selenium WebDriver does not maintain its versions of WebDrivers for different browsers. After that, the Mozilla Foundation started implementing its WebDriver standard, Marionette Driver or Gecko Driver. Similarly, Microsoft also implemented its Edge browser. So, if you use Mozilla Firefox version 46 or above, you must use the GeckoDriver.
Steps To Follow For Using Selenium GeckoDriver
- Download the GeckoDriver from the Official Mozilla GitHub page link at the end of the page; you can get different drivers for different environments, 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 code below.
How to Run the Selenium Test With Setup System.setProperty?
You can run your script By clicking on the Java file in the Package Explorer section, hovering over “Run As,” and selecting “Java Application.” you can try this way: Click on Eclipse code and Click Run As > Java Application.
Note: For Copying the Location of the 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, import the following 2 packages
- : import org.openqa.selenium.WebDriver: It references the WebDriver interface required to instantiate a new web browser.
- import org.openqa.selenium.firefox.FirefoxDriver References the FirefoxDriver class required to instantiate a Firefox-specific driver on the browser instance instantiated using the WebDriver interface.
Let’s understand the use of Statements.
In Selenium, we have different WebDrivers for different browsers. For accessing the Firefox browser, we have GeckoDriver; for the Chrome browser, we have chromeDriver; and for the Internet Explorer browser, we have IEDriver. As in the above automation script, we are trying to launch in the Firefox browser, so let’s understand the below commands in detail:
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 the instantiated “FirefoxDriver” class.
If you don’t know, you can read our post on the interface, where we are trying to share the interface in Java in detail. An Interface is a contract, so whichever class implements those interfaces must provide the implementation of all those methods defined inside that interface, as an interface has only abstract methods. That’s why you are not allowed to instantiate an object of the interface. If you try to create an interface object like the below statement, you will see a compilation saying, “Cannot instantiate the type WebDriver.”
WebDriver driver = new WebDriver();
So, for instantiated driver objects, we need classes like FirefoxDriver or ChromeDriver classes, which are implemented in the WebDriver interface; because of this reason, we are writing like:
WebDriver driver = new FirefoxDriver();
Then one more question may arise in your mind: we can create a direct object of FirefoxDriver or ChromeDriver class like the below:
FirefoxDriver driver = new FirefoxDriver();
Then why are we 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 to the WebDriver interface to help in multi-browser testing with the help of the same driver object; we only 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 see, many logs are generated in the Eclipse console area when trying to run the above program. 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 will not delete the GeckoDriver/Marionette logs. We are only adding a 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 the logs we want to see.
Code to Disable Firefox Logs?
If you see the below code, 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");
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 statement below, then that will help you store the log file in the temporary Windows folder. So, there is 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, and you will get the log file.
Selenium Script Execution In Chrome Browser
In our early post, we saw how to run the selenium script to automate it in the Firefox browser using GeckoDriver. Now, we will learn how to set up Selenium ChromreDriver in multiple ways and see the automation script to launch the Chrome browser using Selenium.
Note: This is part of the Selenium tutorial series, so please ensure you have installed the latest version of Selenium WebDriver to avoid compatibility issues with the Chrome browser.
What tool versions are we going to use for the Selenium ChromeDriver setup?
For the script below, we have used different versions of 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?
WebDriver is responsible for the launch and communication with the browsers. So, we are using the ChromeDriver to communicate with the Chrome Browser, which helps WebDriver 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. For that, we have written lines of code below.
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 Selenium WebDriver step by step:
- You can download the latest version of the ChromeDriver using this link.
- Click On the latest version of ChromeDriver, and you can see we have marked the latest version, ChromeDriver 76.0.3809.25.
- When you click on the link, it will redirect you to another URL from where you can download the latest version of Chrome driver for different environments like Mac, Windows, and Linux.
- As we use a Windows system, you need to download chromedriver_win32.zip, and those using different environments 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 to the next phase, which is how to set up ChromeDriver for your project.
We have used System.setProperty to mention the type of driver we will use and the ChromeDriver’s location. 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 fail, 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 downloaded the other version, ChromeDriver 75.0.3770.90. After making those changes, your script will run smoothly.
Disable Chrome Info Bar Message Using ChromeOptions
If you have noticed, whenever we are running our script, it will launch a Chrome browser and show an info bar with the message “Chrome is being controlled by automated test software.” So we can remove that message from the Chrome browser using the disable-info bars argument from the ChromeOptions class. The code looks something like the 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, you will not see the Chrome info bar again in your browser.
How do you maximize the Chrome Browser using Chrome options?
It’s always a group approach of automation testing to 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 the ChromeOptions class; let’s know how we can 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 customize with these options and a few other settings you can learn from here.
Very Detailed and Clear instructions.. Thanks!!
Thanks For such kind words
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.
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
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.
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
Really Impressed the way you have structured the every thing in clear in all the way to referrsh at one place
We Glad that you like this post