Important Selenium webdriver commands of 2021

In this series of  tutorial we will learn about all the exhaustive selenium webdriver commands starting from the very basic selenium commands to the advance Selenium webdriver commands in the below order of articles : 

Basic Selenium Webdriver commands -Questions: 

Intermediate Selenium webdriver commands -Questions:

Advance Selenium WebDriver Commands -Questions:

Selenium basic commands- Answers: 

selenium webdriver commands
Selenium webdriver commands

Selenium navigate to url :

In Selenium Webdriver if we want to navigate or open any specific URL through our browser then we can do it in majorly two different approaches one is with the get() method and another one with navigate , we will take a look at how it could be done : 

public void getUrl(String url) {
  try {
     driver.get(url);
     BASE_LOGGER.info("Successfully navigated to the URL as :  " + url);
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to navigate to URL  : " + url + " with the error as : " + exceptionData);
  }
}

The code you can write to navigate url is driver.get(“http://example.com”) whereas the driver is the Webdriver instance of the Selenium WebDriver interface.

visit here to understand how to launch all browser in Selenium.

How does the get method works internally in Selenium : 

Once this get() method gets called from your test script then Webdriver reference i.e. the driver will wait till the page is loaded , actually the get() method internally triggers onload function which returns the handle to your driver reference once the page is fully loaded.

Selenium navigate forward and navigate back :

Another approach to navigate to the url with the browser history is by using the navigate() method , where the Selenium uses the history of the browser to navigate forward or navigate back with you respective URLs such as : 

Selenium navigate forward

public void navigateForward() {
  try {
     driver.navigate().forward();
     BASE_LOGGER.info("Successfully navigated forward" );
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to navigate with the error as : " + exceptionData);
  }
}

Selenium navigate Back : 

public void navigateBack() {
  try {
     driver.navigate().back();
     BASE_LOGGER.info("Successfully navigated Back to the URL ");
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to navigate Back to URL  : with the error as : " + exceptionData);
  }
}


Selenium refresh page

We can use refresh() method from Selenium navigate 

public void seleniumRefreshPage() {
  try {
     driver.navigate().refresh();
     BASE_LOGGER.info("Successfully done the Selenium Refresh Page ");
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to perform Selenium Refresh Page : with the error as : " + exceptionData);
  }
}

Selenium click

In order to perform any click operation with Selenium click we have to use method called click() in below approach , there are other ways to perform click operation on any of the WebElement in Selenium ie by using JavaScriptClick which is very useful sometimes depending on situations where your normal Selenium click method is working in a very stable manner , there are some cases where if you are automating with IE browser and  if the Web Application under test is build in some sort of bootstrap JS then normal selenium click method might not work sometime , in those case you could use Javascript click method .

public void safeClick(By element) {
  try {
      driver.findElement(element).click();
     BASE_LOGGER.info("Safeclick operation has been performed for the locator : " + String.valueOf(element));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing Safeclick on the element : " + element);
  }
}

You can pass the element using different locator strategies(ie xpath, name, css etc) in the method called findElement() and then perform the click() method operation like above .

Selenium sendkeys

When we need to enter some text in some text box via Selenium we make use of the Selenium sendkeys() method by passing the “Text to be entered ” as the parameter in the method sendKeys(“Text to be entered”) and similar to the click() method this method is also applied to any webElement(here web text box) so we have to use driver.findElement to send the Text to that TextBox .

The Sample code goes like this : 

public void enterTextIntoElement(By element, String textToBeEntered) {
  try {
     driver.findElement(element).sendKeys(textToBeEntered);
     BASE_LOGGER.info(
           "enterTextIntoElement operation has been performed for the locator : " + String.valueOf(element));
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("enterTextIntoElement operation has been failed for the locator : "
           + String.valueOf(element) + " with the exception i.e : " + exceptionData);
  }
}

Selenium clear text field

If we want to clear any data from a previously filled textfield, we can use the method called clear() and also by the help of Keys Class in Selenium we can do so , through which we can take the Keyboard Operations directly along with keyboard shortcuts :

To clear the Data with the help of clear() method we can write in the below approach: 

public void clearField(By element) {
  try {
     driver.findElement(element).clear();
     BASE_LOGGER.info("ClearField operation has been performed for the locator : " + String.valueOf(element));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("ClearField operation has been failed for the locator : " + String.valueOf(element)
           + " with the exception i.e : " + exceptionData);
  }
}

By using the Keys class we can also clear the Text fields in the following approach.

Selenium maximize window

While working with the Browser Automation if we have to Maximize the Window in Selenium then we could use the following approaches : 

Selenium Maximize Window by using Maximize() method :  

public void maximizeWindow() {
  try {
     driver.manage().window().maximize();
     BASE_LOGGER.info("Successfully Maximized the Window");
  } catch (Exception e) {
     BASE_LOGGER.info("Exception Occured while Maximizing the Window As : " + e.getCause().getMessage());
  }
}

Selenium Maximize Window by using ChromeOptions for ChromeBrowser:

By using the below method we are setting a chrome browser instance for Webdriver in maximized mode and the returned driver session will continue to the same feature(ie maximize window )for further web operation as per the script.

public WebDriver openBrowserInMaximizeWindow(){
  try {
     ChromeOptions options = new ChromeOptions();
     options.addArguments("start-maximized");
     WebDriver driver = new ChromeDriver(options);
    
  }catch(Exception e){
     BASE_LOGGER.error("Exception encountered with  : " + e.getCause().getMessage());
  }
  return driver;
}

Selenium minimize window

We can minimize the window using Selenium minimize() command with the following approach :  

public void minimizeWindow() {
  try {
     driver.manage().window().minimize();
     BASE_LOGGER.info("Successfully Minimized the Window");
  } catch (Exception e) {
     BASE_LOGGER.info("Exception Occured while Minimizing the Window As : " + e.getCause().getMessage());
  }
}

Selenium close browser:

To close the browser in Selenium we use close() method in the below approach : 

public void closeCurrentWindow() {
  try {
     if (null != driver) {
        driver.close();
        BASE_LOGGER.info("Successfully closed the current Window/Browser");
     } else {
        BASE_LOGGER.info("Unable to close the current Window/browser instance as Its NULL");
     }
  } catch (Exception e) {
     BASE_LOGGER.info("Exception occurred while closing the current Window/Browser");
  }
}

Selenium quit browser

To quit all the browser instances in Selenium we use quit() method in the below approach : 

public void quitBrowser() {
  try {
     if (null != driver) {
        driver.quit();
        BASE_LOGGER.info("Successfully QUIT Browser");
     } else {
        BASE_LOGGER.info("Unable to QUIT the Browser as Its NULL");
     }
  } catch (Exception e) {
     BASE_LOGGER.error("Exception occurred while QUITING Browser");
  }
}

Difference between driver.close() and driver.quit()in Selenium  :

Intermediate Selenium webdriver commands – Answers:

Dropdown in selenium:

In Webpage DOM structure, the dropdown is implemented by either Select or input Tage of HTML .To work with Dropdown with Selenium and perform certain 

web operations on the dropdowns, we need to use “Select” class from Selenium WebDrivers API as part of “org.openqa.selenium.support.ui” package from Selenium WebDriver. 

There are 2 different problem statement or ask while working with the Selection of DropDown in Selenium : 

Selection of single Element in a Dropdown at a time

In the below approach we can work with Dropdown:  

Step One :

You have to create a handle for the DropDown WebElement using Select class Object creation in the below manner :

Select select = new Select(WebElement webelement);

Step two : 

There are 3 different approaches to select the value from the dropdown in Selenium , we could use any of the below methods to select the value from dropdown in Selenium : 

Here is the below Approach we can take to select value from Dropdown : 

Dropdown in selenium- Approach One : 
In the Approach One you can use the text which is visible of the Desired Selection of the Webelement .

public void selectFromDropDownByText(By locator, String visibleText) {
  try {
     Select dropDownElement = new Select(driver.findElement(locator));
     dropDownElement.selectByVisibleText(visibleText);
     BASE_LOGGER.info("SelectFromDropDownByText operation has been performed for the locator : "
           + String.valueOf(locator));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing selectFromDropDownByText on the element : " + locator);
 }
}

In the above method you can pass the locator of the dropdown and the visible text which you want to select from the dropdown then it will perform the desired operation is Selecting the expected dropdown element . 

Dropdown in selenium- Approach Two :

In this Approach you select the Webelement by using the value attribute  of the desired WebElement’s selection from the dropdown : 

public void selectFromDropDownByValue(By locator, String visibleText) {
  try {
     Select dropDownElement = new Select(driver.findElement(locator));
     dropDownElement.selectByValue(“Desired Webelement’s value ”);
     BASE_LOGGER.info("selectFromDropDownByValue operation has been performed for the locator : "
           + String.valueOf(locator));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing selectFromDropDownByValue on the element : " + locator);
  }
}

In the above method you can pass the locator of the dropdown and the value attribute of the WebElement of which you want to select from the dropdown then it will perform the desired operation is Selecting the expected dropdown element . 

Dropdown in selenium- Approach Three :

In this Approach you select the Webelement by using the index(order of the WebElement in the HTML select tag )  of the desired WebElement’s selection from the dropdown, index generally starts from 0 :

public void selectFromDropDownByIndex(By locator, String visibleText) {
  try {
     Select dropDownElement = new Select(driver.findElement(locator));
     dropDownElement.selectByIndex(5);
     BASE_LOGGER.info("selectFromDropDownByIndex operation has been performed for the locator : "
           + String.valueOf(locator));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing selectFromDropDownByIndex on the element : " + locator);
  }
}

In the above method you can pass the locator of the dropdown and index/order of the WebElement(in the Select Tag of the Dropdown ) of which you want to select from the dropdown then it will perform the desired operation is Selecting the expected dropdown element .

Selection of multiple Elements in a Dropdown at a time 

It depends on the HTML DOM structure and implementation whether any dropdown element is allowed to have multi selection of Elements . To select multiple elements in Selenium we have to follow below two steps : 

Step One : Check whether the DropDown WebElement allows the multi selection by using the method isMultiple() , this returns boolean as true or false.

Step Two : if the above step returns true then the dropdown allows multi selection .And after this we can use the above discussed any/all of the three different approaches to select multiple values and perform any desired operations ..

So to conclude here below is the sample code :

WebElement element =driver.findElement(By.xpath("XPATH OF THE DropDown"));
Select selectMultiple = new Select(element);
if(selectMultiple.isMultiple()){
   selectMultiple.selectByIndex(1);
   selectMultiple.selectByIndex(2);
//Similarly We could use other approaches/method for selecting dropdown elements such as selectByVisibleText or selectByValue
}

Drag and drop in selenium :

In the segment of tutorial we will learn all the different different approaches of performing Drag and Drop in Selenium such as : 

What is drag and drop in Selenium and where its used : 

Drag And Drop is a specific operation when users navigate to your web applications and try to perform operation(dragging by mouse move) on some webelement which can move freely over the application and can be dropped in some other location of the webpage of that application . 

Here the element which is being dragged is called a Source WebElement and the element where it’s being dropped is called a Destination WebElement . 

To Perform the above scenarios via Automation with Selenium we need to drag and drop functionalities provided by Selenium .

Different Approaches of Drag and Drop in Selenium :

Drag and Drop in Selenium using Build() method : 

How Build() method internally works :

build() method from the Actions class in Selenium which is part of the package org.openqa.selenium.interactions internally generates a composite actions 

by combining all the actions which have been called or triggered before calling the build() method.

For an example :

new Actions(driver).clickAndHold(sourceElement).moveToElement(destinationElement)
       .release(destinationElement).build();

The above statement to perform drag and drop operation build is being used to bind the previous actions such as clickAndHold, moveToElement and release methods.

Here is the below code snippet to perform the Drag and Drop in Selenium using build method of Actions class: 

public void dragAndDrop(By source, By destination) {
   try {
       WebElement sourceElement = driver.findElement(source);
       WebElement destinationElement = driver.findElement(destination);
       Actions builder = new Actions(driver);
       Action dragAndDrop = builder.clickAndHold(sourceElement).moveToElement(destinationElement)
               .release(destinationElement).build();
       dragAndDrop.perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

Drag and Drop in Selenium using dragAndDrop() method :

How dragAndDrop() method internally works :

dragAndDrop(sourceWebElement,destinationWebElement) method basically takes two arguments one is source and another one is destination webelement. 
dragAndDrop removes the need of clickAndHold,moveToElement,release methods in Action class, it internally handles all the scenarios which are performed by these methods .

Here is the below code snippet for performing  dragAndDrop with the method dragAndDrop :

public void dragAndDropOps(By source, By destination) {
   try {
       WebElement sourceElement = driver.findElement(source);
       WebElement destinationElement = driver.findElement(destination);
       Actions builder = new Actions(driver);
       builder.dragAndDrop(sourceElement,destinationElement).perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

Drag and Drop in Selenium using dragAndDropBy() method:

How dragAndDropBy(WebElement source, int xOffset, int yOffset) method internally works :

The method dragAndDropBy() takes 3 arguments which are : 

Source WebElement : the Element which is dragged ie the source element 

xOffset : horizontal move offset of the destination location 

yOffset : vertical move offset of the destination location 

Internally this method takes the source webelement and moves and releases it to the destination location. This method is useful if you want to move any source webelement to any pixel locations .

Below is the code snippet for the DragAndDropBy in Selenium :

public void dragAndDropByOps(By source, int xOffSet,int yOffSet) {
   try {
       WebElement sourceElement = driver.findElement(source);
       Actions builder = new Actions(driver);
       builder.dragAndDropBy(sourceElement,xOffSet,yOffSet).build().perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

Visit here for the rest of the advanced sets of Intermediate Selenium webdriver commands.

Advance Selenium WebDriver Commands -Answers:

Double click in selenium :

To replicate the operation ie double click in Selenium via mouse we need to Perform double click via Actions class in Selenium  and we can do it in the below approach : 

public void doubleClick(By locator) {
   try {
       WebElement element = driver.findElement(locator);
       Actions actions = new Actions(driver);
       actions.doubleClick(element).perform();
       BASE_LOGGER.info("Performed the double Click on the Element  : " + locator);
   } catch (StaleElementReferenceException e) {
       BASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
   } catch (NoSuchElementException e) {
       BASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
   } catch (Exception e) {
       BASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
   }
}

The above code snippet is a method which basically takes an argument as Locator i.e. the WebElement on which the double click has to be performed.

Contextclick in selenium :

To replicate the context click or right click operation via mouse we need to Perform context click method via Actions class in Selenium  and we can do it in the below approach : 

public void rightClick(By locator) {
   try {
       WebElement element = driver.findElement(locator);
       Actions actions = new Actions(driver);
       actions.contextClick(element).perform();
       BASE_LOGGER.info("Performed the context Click on the Element  : " + locator);
   } catch (StaleElementReferenceException e) {
       BASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
   } catch (NoSuchElementException e) {
       BASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
   } catch (Exception e) {
       BASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
   }
}

For the detailed Advance Selenium webdriver commands visit here.. Also to get understanding of the Actions class in Selenium and its implementations visit here .

Critical FAQs : 

What is manage() in Selenium ?

driver.manage() returns an reference of implementation of WebDriver.Options Interface.Options interface is an interface for managing and handling actions in a browser menu such as : 

For exhaustive sets of Selenium interview Questions -Critical and Advanced sets visit here .

Conclusion :

In this section of the tutorial we covered the Basic Selenium webdriver commands , Click here to learn the Intermediate and Advance Selenium webdriver commands. To learn Selenium from Scratch click here .

Leave a Comment