Top 25 Selenium Webdriver Commands for Test Automation


In this tutorial you will learn about basic Selenium Webdriver Commands which would be the backbone of your GUI automation scripts. We have divided the commands in to different categories so that you can grasp them without difficulty.





Table of Content

1. Selenium Browser Commands

2. Get Commands

3. Navigation Commands

4. Web Element Commands

5. Select Dropdown Commands



1. Selenium Browser Commands

Browser commands are the starting point of your Selenium Webdriver script. These commands used to launch browser, maximize it, open URL to be tested and other navigation commands.

i. Set Path of browser/driver executable:

  • It is the starting point of the webdriver script. 
  • You have to download the browser executable file for the browser and make sure it is compatible with the version of your browser.
  • For example, for firefox you have to download geckodriver.exe and place in your project.
  • Download geckodriver executable from this link - https://github.com/mozilla/geckodriver/releases
  • Similarly for other browsers you have to download their browser/driver executables.
  • Below is an example for Firefox code, where in first line we have to provide the path of the geckodriver or any driver that we are using.
  • In second line we are setting that value in a property variable named, webdriver.gecko.driver.
// Set Path of driver executable
String driver_executable_path = "./src/com/techlistic/utils/geckodriver.exe";

System.setProperty("webdriver.gecko.driver", driver_executable_path);


ii. Launch Browser:

With this command we will be launching our browser (session) with selenium. Selenium will launch the 
browser at the beginning of the execution. In the example code below:
  • WebDriver is an interface, of which we are creating an object.
  • FirefoxDriver is a class of which we are initialising the webdriver object.
// Launch Browser - Creating a Firefox instance
WebDriver driver = new FirefoxDriver();

If you want to execute your tests on some other browser, say chrome, Safari, Opera and IE then you have to use the following code. 
  • You just have to replace the Class name to the browser name.
  • And you also have to download the browser specific driver executable, like we downloaded geckodriver.exe for Firefox. But for chrome browser we have to use chromedriver.exe and same for others.
  • Link for downloading chromedriver (make sure chromedriver version is compatible with your browser version) - https://chromedriver.chromium.org/downloads
// For Chrome
String driver_executable_path = "./src/com/techlistic/utils/chromedriver.exe";
WebDriver driver = new ChromeDriver();

// For Safari
String driver_executable_path = "./src/com/techlistic/utils/safaridriver.exe";
WebDriver driver = new SafariDriver();

// For Opera
String driver_executable_path = "./src/com/techlistic/utils/operadriver.exe";
WebDriver driver = new OperaDriver();

// For IE
String driver_executable_path = "./src/com/techlistic/utils/iedriver.exe";
WebDriver driver = new InternetExplorerDriver();

iii. Maximize Browser
  • As the name suggests this command is used to maximise browser window. It is generally used at the starting of script.
iv. Make Browser Full Screen
  • This command is used to make the browser window fullscreen. It is occasionally used.
v. Minimize Browser
  • This command is used to browser window.
vi. Set Size of Browser Window
  • This command is used to if there is a special case where you want to test your cases in a specific size of the window.
vii. Close Browser
  • This command is used to close the current browser window. It is generally used at the end of script.
viii. Quit Browser
  • This command is used to close all the browser windows opened by Webdriver. It is used at end of the script
Syntax:

// Maximize Browser
driver.manage().window().maximize();

// Make Browser Window Full Screen
driver.manage().window().fullscreen();

// Minimize the browser
driver.manage().window().setPosition(new Point(0, -1000));

// Set Size of browser
driver.manage().window().setSize(new Dimension(1920, 1080));

// Close Current Browser Window
driver.close();

// Close All Browser Windows
driver.quit();

2. GET Commands

i. Open URL
  • This command is used to open URL. You can provide a string which contains a url.
// Open URL 
driver.get("https://www.techlistic.com/");

// Or 
String url = "https://www.techlistic.com/";

driver.get(url);

ii. Get Title
  • This command is used to obtain title of the page. It returns a string.
// Get Title
driver.getTitle();

// Code implementation example
String pageTitle = driver.getTitle();
// Validate Page Title
if(pageTitle == "Techlistic - Home") {
 System.out.println("Test Passed.");
}
else {
 System.out.println("Test Failed.");
}

iii. Get Current URL
  • This command is used to get url of current page. It returns a string.
// Get Current URL
driver.getCurrentUrl();

//Code implementation example
String pageURL = driver.getCurrentUrl();

// Validate Current Page URL
if(pageURL == "https://www.techlistic.com/p/selenium-tutorials.html") 
{
 System.out.println("Test Passed.");
}
else 
{
 System.out.println("Test Failed.");
}

iv. Get Page Source
  • This command is used to get the source code of the web page. It returns a string.
// Get Page Source
driver.getPageSource();

// Or
String sourceCode = driver.getPageSource();


3. Browser Navigation Commands

These commands are used to move forward and back using browser history.
  1. navigate().to() - It is used to navigate to a specific URL.
  2. navigate().forward() - It is used to navigate using browser's forward button.
  3. navigate().back()It is used to navigate using browser's back button.
  4. navigate().refresh() - It is used to refresh the browser.
Code:

package com.techlistic.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrowserNavigationCommands {

	public static void main(String[] args) {

	// Expected Title
	String expectedTitle = "Techlistic";

	// Set Path of the Chrome driver
	System.setProperty("webdriver.chrome.driver", "./src/utils/chromedriver.exe");

	// Launch Firefox browser
	WebDriver driver = new ChromeDriver();

	// Open URL of Website
	driver.get("https://www.techlistic.com");

	// Maximize Window
	driver.manage().window().maximize();

	// Navigate directly to some URL
	driver.navigate().to("https://www.techlistic.com/p/java.html");

	// Navigate Back
	driver.navigate().back();	

	// Navigate Forward
	driver.navigate().forward();

	// Refresh Page
	driver.navigate().refresh();

	// Close Browser
	driver.close();

	}
}

Selenium example code

package com.techlistic.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class A_01_BrowserCommands_Test {

	public static void main(String[] args) {
	  
	  // Expected Title
	  String expectedTitle = "Techlistic";

	  // Set Path of the Chrome driver
	  System.setProperty("webdriver.chrome.driver", "./src/utils/chromedriver.exe");

	  // Launch Firefox browser
	  WebDriver driver = new ChromeDriver();

	  // Open URL of Website
	  driver.get("https://www.techlistic.com");

	  // Maximize Window
	  driver.manage().window().maximize();
	  
	  // Get Title of current Page
	  String actualTitle = driver.getTitle();
	  System.out.println("Title fetched: "+ actualTitle);
	  
	  // Validate/Compare Page Title
	  if(expectedTitle.equals(actualTitle)) {
	   System.out.println("Test Case Passed.");
	  }
	  else {
	   System.out.println("Test Case Failed.");
	  }
	  
	  // Close Browser
	  driver.close();
	  
	}
}

4. WebElement Commands

WebElement commands are the most important and basic commands, which we use most of the time in automation scripts. These commands are used to enter text, click on links, click on buttons, selecting dropdowns, check radio buttons, select checkboxes, select date from date picker etc. You can practice all web element commands here, Selenium Practice Form.

i. Clear - This command is used to clear the text from the text box. This command is generally used to clear pre-filled text values from text boxes. We should use this command before sendKeys() to make sure that textbox is empty.

// Clear Command - to clear the already filled data in text box
driver.findElement(By.className("some-class")).clear();

// OR

// Implementation with WebElement
WebElement FIRSTNAME =  driver.findElement(By.id("some-id"));
FIRSTNAME.clear();

ii. SendKeys - This command is used to enter text in any text box. Like., username, password, description etc.

/* sendKeys()
 *  This command is used for entering value in a Text box
 */
driver.findElement(By.xpath("/some/xpath")).sendKeys("Some Value");


// OR

// Implementation with WebElement
WebElement FIRSTNAME =  driver.findElement(By.id("some-id"));
FIRSTNAME.sendKeys("Any Text value");

iii. Click - This command is used to click on any type of web element like., 
    • Link
    • Button
    • Radio button
    • Check box
    • Date Picker / Calendar
/* click() 
 */
driver.findElement(By.id("some-id")).click();

// OR

// Implementation with WebElement
WebElement LOGIN_BUTTON =  driver.findElement(By.id("some-id"));
LOGIN_BUTTON.click();

iv. GetText - This command is used to get value/text of a web element in string form. It's a very important command. 

/* getText() Command
 *  This command is used to get value/text from a WebElement
 */
String textValue = driver.findElement(By.xpath("/some/xpath")).getText();

// OR

// Implementation with WebElement
WebElement SOME_LINK =  driver.findElement(By.id("some-id"));
String linkValue = SOME_LINK.getText();
System.out.println(linkValue);


v. GetCssValue - This command fetch the value of the CSS property associated with given web element. It is used to get the color of the font/background, font-style, font-size etc.

/* getCssValue() Command
 */
WebElement HEADING =  driver.findElement(By.id("some-id"));

String color = HEADING.getCssValue("color");
System.out.println(color);

vi. isDisplayed - This command checks whether an element is visible on the current page or not. It returns a true if element is visible and returns false if element is not visible.

/* isDisplayed()
 */
WebElement loginButton =  driver.findElement(By.id("some-id"));
boolean isLoginDisplayed = loginButton.isDisplayed();

vi. isSelected - This command checks whether an element like Select box, checkbox or radio button is selected or not. It returns true if element is selected or checked and vice-versa.

/* isSelected()
 */

WebElement age =  driver.findElement(By.id("some-id"));
boolean isAgeSelected = age.isSelected();

vi. isEnabled - This command is used to check whether an element is enabled or not on the current webpage. It's important to know that Selenium can only interact with those elements which are enabled, if an element is disabled then we cannot execute any command on that element. It'll throw exception.

/* isEnabled()
 */

WebElement login =  driver.findElement(By.id("some-id"));
boolean isLoginEnabled = login.isEnabled();

if (isLoginEnabled){
    login.click()
}
else{
    System.out.println("Login button is not enabled")
}

5. Select Dropdown Commands

Select commands can be used to select and de-select dropdown options. We can select and un-select a dropdown by 3 different commands. You can practice all Select commands here, Selenium Practice Form.

i. selectByIndex() - We can select any dropdown value by just giving it's index/position at which it is present. Index starts from 0. So, if we have to select 2nd dropdown option then we have to give it's idex as 1, for e.g., selectByIndex(1)

ii. selectByVisibleText() - This command is used select dropdown by the it's text value. Like if I have to select option Europe then the command would be selectByVisibleText("Europe").

iii. selectByValue() - This command is used to select dropdown option by providing the it's option tag's value attribute. You have to look in the html for value attribute of it's option tag. 

Something like,  
[option value = "As"] Asia [/option]

So the command would be - selectByValue("As")

Similarly, we have deselect commands which acts in the opposite way.

iv. deselectAll() 
v. deselectByIndex()
vi. deselectByVisibleText()
vii. deselectByValue()


/* Select Commands
* selectByIndex() * selectByVisibleText() * selectByValue() */ WebElement DROP_DOWN = driver.findElement(By.xpath("/select")); // Create object of Select Class Select select1 = new Select(DROP_DOWN); // Option 1 select1.selectByIndex(2); // Option 2 select1.selectByVisibleText("Edam"); // Option 3 select1.selectByValue("Edam"); // Similarly, De-Select Commands select1.deselectAll(); select1.deselectByIndex(index); select1.deselectByValue(arg0); select1.deselectByVisibleText(arg0);

viii. Code to get all options from a dropdown

// Example - Get all options from a dropdown and print them
WebElement select = driver.findElement(By.tagName("select"));

// Get all options in a list with tagname 'option'
List allOptions = select.findElements(By.tagName("option"));

// Print all options in for each loop
for (WebElement option : allOptions) {
 System.out.println(String.format("Value is: %s", option.getAttribute("value")));
  option.click();
}

ix. isMultiple() - This command is used to check whether a selected web element is muti-select box or not. It returns boolean value either true or false.

x. getAllSelectedOptions() - This command is used to get all selected dropdown options for a multi-select box.

WebElement DROP_DOWN = driver.findElement(By.id("select"));

// Create object of Select Class
Select selectBox = new Select(DROP_DOWN);
// Check if checkbox is multi-select or not, return True or False
boolean isMultiSelect = selectBox.isMultiple();

if (isMultiSelect){
    selectBox.selectByIndex(2);
    selectBox.selectByIndex(4);
}
else{    
	System.out.println("Not a multi select box.");
	selectBox.selectByIndex(2);
	// Returns WebElement of first selected option 
	String firstSelected = select1.getFirstSelectedOption();
	System.out.println(option);
}

// Get all selected options, returns a list
List selectedOptions = select1.getAllSelectedOptions();
// Print all selected options
for (String option : selectedOptions ) {
	System.out.println(option);
}

Happy Learning!

Locators and Find Element Commands  << Previous      ||      Next >>  Actions Class in Selenium

Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.

Comments

  1. Excellent. Content Simplified in its best way. Please post on pending areas in the index.

    ReplyDelete
  2. very helpful to practise these Assignments

    ReplyDelete

Post a Comment

Popular posts from this blog

10 Best Demo Websites for Selenium Automation Testing Practice

Automate an e-Commerce website with Selenium Webdriver

How to Handle Dynamic Web Table in Selenium WebDriver

Top 50 Selenium Webdriver Interview Questions

Automate Browser Actions and Menu links with Selenium Webdriver