Skip to main content

First Selenium script using Java

How to configure browser driver

    The first step is to set the browser driver path to the System. Command will be different based on the browser type

        Chrome browser
            System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");
        Firefox browser
            System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

setProperty method is used to set the property name and value 

Property name - webdriver.chrome.driver: This is common for chrome browser
Property value - G:\\chromedriver.exe: This is where the chrome driver executable file is located in the local. To avoid any blocker use a chrome driver that matches your browser version.

Initializing WebDriver

        WebDriver driver = new FirefoxDriver();

WebDriver is a predefined interface and to access its ability it should get imported using import org.openqa.selenium.WebDriver; 

The object should be created for class FirefoxDriver of type WebDriver because WebDriver is an interface. So, the Corresponding class should get imported import org.openqa.selenium.firefox.FirefoxDriver;

Ways to launch URL in selenium

1. get() - This is one of the methods available in the webdriver interface. We can able to access this method using object reference created for driver class(ChromeDriver).
                driver.get("https://www.amazon.com/");
         
        If the URL is provided using the above way, it is hard to change the URL in the future. So mostly these URLs were saved as a string value and that was passed to the .get() method. This can also be written like below
            
                String landingURL = "https://www.amazon.com/";
                driver.get(landingURL);

2. navigate().to() - This is another method used to navigate to a URL. This method is the abstraction of the Navigation interface which is the inner interface of WebDriver. 
                String landingURL = "https://www.amazon.com/";
                
driver.navigate().to(landingURL );

How to close the browser

    Once the test is over, the browser needs to be closed. This is done using .quit() method. Which is also one of the methods in the WebDriver interface. 
    
                driver.quit();

Full Program

package navigation;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstSeleniumScript {
	public static void main(String[] args) {
	  System.setProperty("webdriver.chrome.driver",
          "F:\\Selenium drivers\\chromedriver.exe");	
	  String landingURL = "https://www.amazon.com/";
	  WebDriver driver = new ChromeDriver();
	  driver.get(landingURL);
	  driver.quit();
	}
}
Let us discuss about other concepts in upcomming posts

Comments