Table of Contents
Introduction
In this tutorial, we will develop our first Selenium script. This is a basic script to understand the foundational concepts of writing code in Selenium. We will learn about the import statement, Webdriver initialization, launching a webpage and then safely closing the launched webpage. The scenario which we are automating consists of the following steps:
- launch the Facebook login page
- fetch the title of the page
- print the title on the console
- exit the webpage
Now let us see how we can automate the above manual steps using Selenium WebDriver.
Pre-Requisites
We need to do the environment setup before we can write the automation code. The pre-requisites to develop the very first Selenium Webdriver script are
- Download and install Java
- Set up Java environment variables
- Install Eclipse IDE
- Download Selenium client Jars
- Set Up Eclipse project with Selenium client Jars
In case you have missed any of the above set up, please refer to the individual tutorials available in our course for them.
Decoding the Selenium code
We have created a Java project in Eclipse and a package inside it. We have also created a java class which is open in the editor. All selenium jars are present in the Referenced Libraries. Our Java project looks like below now. With this, we are all set to start writing our automation code.
Initialize the driver
To use Selenium WebDriver, we need to create an object of it and initialize it with the browser driver in which we wish to execute the automation script. I am using ChromeDriver to start with by initializing it as shown in the code below. We can execute the code in any browser like FireFox, IE by using driver corresponding to it.
WebDriver driver = new ChromeDriver();
It will show compiler error by showing red dotted underline below WebDriver and ChromeDriver. These errors are there because we need to import Selenium packages containing WebDriver and ChromeDriver classes. To resolve the compilation error shown for WebDriver and ChromeDrivers, just mouse hover over the error and click on import ‘WebDriver’. It will add an import statement at the top of the code to resolve the compilation error. Refer to the image given below for better understanding.
Similarly to resolve the compiler error for ChromeDriver, import ‘ChromeDriver’. The import statement to import related package will get added at the top.
Next, let us write the Selenium code for our manual scenario in our test class. Refer to the code below:
package seleniumAutomationTests; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class MyFirstTest { public static void main(String[] args) { // TODO Auto-generated method stub //declare instance of WebDriver and run using chromedriver WebDriver driver = new ChromeDriver(); //load the webpage of application under test driver.get("https://www.facebook.com"); //get the title of the page in a string variable String pageTitle = driver.getTitle(); //print the page title on console System.out.println(pageTitle); //close the browser driver.close(); } }
Statements of code
All the different statements of code are explained below in detail:
- package statement: It tells the package in which the current class is located.
- import statements: import is a Java keyword which is used to import java built-in and also user-defined packages into your java source file. It lets your class refer to another class that is in a different package by just using the name of the class. ‘*’ character is used to include all the classes of the package. Here we are importing WebDriver and ChromeDriver classes of respective packages.
- public static void main(String[] args): main() method is the entry point to any Java application. When Java interpreter runs an application, it starts it by making the call to the main() method.
- WebDriver driver declaration: WebDriver instance driver is initialized as ChromeDriver so that the script runs on chrome browser. WebDriver is an interface which declares methods but does not have their implementations. Implementations of methods are provided by implementing classes like ChromeDriver. This is a typical example of polymorphism where an instance of WebDriver interface behaves as implementing class ChromeDriver. This also helps in achieving multi-browser execution by assigning the driver instance to other browsers driver classes like IEDriver or SafariDriver.
- Adding comments: Comments can be added to the code to increase the readability of the code by inserting “//” characters before the comment line.
Understanding Selenium methods
Now, after understanding this much code for initial setup, we can write the Selenium code to automate the scenario specific steps.
- Launch the Facebook login page: driver.get(“https://www.facebook.com”) launches the web application under test in the chrome browser. After this statement is executed, the script control will land on the webpage location given as string argument to the get method. WebDriver will wait for the page to load fully before it returns the control to the script again. There is one more method driver.navigate().to() which is also used to navigate to the webpage. The basic difference between get() and navigate() methods is that the navigate() method maintains the history so the driver can move back or forward. In case of get() method browser history is not maintained.
- Fetch the title of the page: driver.getTitle() method fetches the page title of the webpage.
- Print the title on the console: System.out.println(pageTitle) prints the value of pageTitle on the console.
- Exit the webpage: driver.close() statement will close the current window of the browser opened by the driver. There is one more method quit() which can be used for quitting the browser completely. It will destroy the WebDriver instance and quit all the windows of the browser.
After writing the code in Eclipse IDE in the test class, the Eclipse window will look as shown in the below image.
Execution
Now we have completed writing the code in the script. Next, we should execute the script to check the output. But to run the script we need to complete one more step. We need to download the browser specific driver like ChromeDriver in our case and set the Path environment variable which points to the location of the driver in the local system.
Download the chrome driver
- First, check the version of the Chrome browser installed in your machine. You can do so by Help > About Google Chrome. Here, it will show the current version installed.
2. Next step is, to download the Chrome browser driver. For that, we need to go to the download section of chromium official site https://sites.google.com/a/chromium.org/chromedriver/.
3. Select the version of Chrome Driver as per the chrome browser in your machine and click on it. With that, it will navigate to a webpage with corresponding executables for different platforms.
4. For windows, select chromedriver_win32.zip and click on it. It will download a zip file. Save this zip file to an appropriate location.
Note: Please select the chrome driver version which matches your Chrome browser version. Otherwise, the chrome browser session will not be established by the script and exception will be thrown. For this reason, decide the suitable version of chrome driver considering the official chrome driver site https://sites.google.com/a/chromium.org/chromedriver/downloads/version-selection.
5. Extract the content of the saved zip file in a folder and you will get chrome driver executable.
Significance of driver location
We have downloaded the chrome driver executable in the system. Now Selenium script will use it to connect to Chrome browser. But, how will Selenium know where is the driver located while running the script? For that, there are two methods to help the script find the driver:
- Set Path variable: We should set the environment variable to point to the location of the driver in the system. Here, we will learn about this method in detail in this tutorial.
- Code changes in the script. We can do the code changes in each test script to tell it where to locate the driver file in the system. Going forward, we will learn about this method in detail in the next tutorial about Test execution in chrome browser.
Set the Path variable
- Go to Control Panel > System and Security > System and click on advanced system settings on the lefthand side of the screen. This will open up the setup window for System Properties.
2. The system settings window will be displayed as shown. It will automatically open the window in the advanced tab. At the bottom right of the window, click the button for environment variables.
3. The Path environment variable points to the binary files of installed software packages. If any external software system needs to access these binary files, it will reach to them using the Path system variable. For adding the entry for chrome driver executable, go to C:\softwares\drivers and copy this folder path.
Path = C:\softwares\drivers
4. Select Path from the list of system variables and click on Edit.
5. On the Edit environment variable screen, click on new and enter the path of the driver folder which is C:\softwares\drivers. Once done, click on OK button which will add an entry for this folder in your systems path variable.
6. Click on OK and you can come out of the system variables setup window. This completes the steps for Path environment variable setup for driver executable.
Now we have completed the Path environment variable setup. We are all set to run the Selenium script now.
Run the script
To execute the script, right click on the java class name and go to Run As > Java Application. With this, the script will start its execution. It will
- Locate the driver at the location set by the Path environment variable.
- Start the chrome browser using the chrome driver
- Launch the application under test
- Fetch the value of page title of the web page and store it in a string.
- Print the page title on the console
- Close the web page and complete the execution of the script.
Checking the output
When we start the execution of our script, the application under test will be started in a new chrome browser window. Then, it will perform the commands provided in the script. Thus, in our case fetch the page title and driver.close() method will close the browser window.
We can observe the output of the script on the console window at the bottom of the Eclipse IDE. As we can see, it printed the page title here.
Conclusion
This tutorial talks about a simple scenario to automate using Selenium WebDriver for Selenium learners. Moreover, it lists the prerequisites of environment setup before writing Selenium code. After setup, we wrote code to automate the manual scenario steps. Also, we executed the code in Chrome browser. Next, we will see how to execute this script in different browsers in the coming tutorials.