Writing the first script

In the last post, we learned about setting up selenium webdriver with eclipse. Today, we will see how we can start writing our scripts. We have already created the project “SeleniumPractice” during setup. So now let’s create one package under our project.

Right click src. Then click on New > Package

frstscrpt1

Give a package name in Name field and click on Finish

frstscrpt2

Under this package, we will create a java class. To create a class

Right click on package name org.seleniumframework. Click on New > Class

frstscrpt3

Give a meaningful name for class in Name field. Select the checkbox public static void main(String[] args) as this will be the execution point for script. After doing this, click on Finish

frstscrpt4

Now, the class LaunchBrowser is created.

frstscrpt5

Here is a code to launch a website

frstscrpt6

First we have to create a webdriver reference variable driver and assign the object of class FireFoxDriver to it so that we can access all the pre-defined methods of FireFoxDriver class. There are other driver classes in selenium such as InternetExplorerDriver, ChromeDriver, SafariDriver, OperaDriver, AndroidDriver, IPhoneDriver, and HtmlUnitDriver. But as we are using only Firefox browser, we need to create object of that driver class.

Then we need to set system property using setProperty method of System class. This methods takes two arguments. First is Name of the system property and Second is the Value of the system property. Hence, we need to provide the name: webdriver.gecko.driver and value is a path of executable file that we copied under Driver folder. So we have given path as .//Driver//geckodriver.exe where a dot(.) represents our default project.

To launch the website, we have a get() method which takes only one argument Website URL. But keep in mind that we need to provide complete URL. If we will write newtours.demoaut.com instead of http://newtours.demoaut.com, we will get f.queryInterface is not a function exception.

The last command is used to maximize the browser window. We have pre-defined methods like maximize(), fullscreen() etc to control browser window.

We can see that there are two errors in the above image. We need to resolve those to execute the script or else our script will not execute. To resolve that, hover the mouse over the error symbol on line 8 and click on it. It will open a suggestion box with some probable suggestions to resolve errors. Click on Import ‘WebDriver’ (org.openqa.selenium).

frstscrpt7

Similarly, we need to import FireFoxDriver package. Click on Ctrl+S to save the changes.

frstscrpt8

Our script is ready for execution.To run this,

Click on down arrow highlighted in the image below. Click on Run As > Java Application

frstscrpt9

This is all for today. Hope you enjoyed this article. If you find this useful then please share this with others as well.

Have a great Day!!!

Leave a comment