Mastering Selenium WebDriver: 25+ Essential Commands for Effective Web Testing

In this tutorial, you will learn about the most important 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 learn Selenium commands without difficulty. This Selenium Commands tutorial has explained you all the commands with Code examples and sample Selenium programs for better understanding.




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 initializing 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 maximize 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 full screen. 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.
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 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();

	}
}

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);
}


Selenium Locator Commands  << Previous      ||      Next >>  What is Actions Class in Selenium?

Author
Passionately working as an Automation Developer from more than a decade. Let's connect LinkedIn.

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
  3. The information you've provided is useful because it provides a wealth of knowledge that will be highly beneficial to me. Thank you for sharing that. Keep up the good work. Web Design Tampa

    ReplyDelete
  4. Nowadays, to complete SEO tasks in minimum time, some SEO service providers use automated tools for directory submission and article submission. sendpulse com

    ReplyDelete
  5. provides digital marketing consultation and lead generation services to small businesses in local markets. He can be contacted through Website Marketing news heraldcorp com

    ReplyDelete
  6. This article provided me with a wealth of information about Full stack web development services for small business. The article is both educational and helpful. Thank you for providing this information. Keep up the good work.

    ReplyDelete
  7. The information you've provided is useful because it provides a wealth of knowledge that will be highly beneficial to me. Thank you for sharing that. Keep up the good work. Graphic Design Company Sydney

    ReplyDelete
  8. The information in the post you posted here is useful because it contains some of the best information available. Thanks for sharing it. Keep up the good work Website Design Company

    ReplyDelete
  9. You have provided valuable data for us. It is great and informative for everyone. Keep posting! also look at this web design agency dubai. I am very thankful to you.

    ReplyDelete

  10. Clipping Path Us is a dedicated clipping path service provider managed by some professional and experienced graphic designers. Our buyers have a good knowledge of our photo editing services and recognize it as one of the best crop path service companies in the world. Clipping Path Service Inc is a model image editing platform. Our clients have benefited their business by using our high quality, professional and affordable Photoshop services. We have more than 150 Photoshop experts to provide all types of image editing tasks. We reportedly provide cropping path, color correction, image masking, neck join, photo retouching, background removal and e-commerce image editing services worldwide. We believe that our clients' success means our success. That is why we are committed to providing high quality work. Clipping Path is an excellent choice for a high quality background removal service from Clipping Path Us. As today's preferred clipping path service provider in Southeast Asia, we provide all types of clipping path services at the lowest price, whether it's image background removal or multi-color correction. So you can rely on us when it comes to road cutting service Clipping path service


    #clippingpath #clippingpathservice #backgroundremoval #imagemasking #dropshadowservice #reflectionshadowservice #photoretouchingservice #colorcorrectionservice #ecommerceimageediting #carimageediting #neckjointservice #ghostmannequinservice #invisiblemannequinservice #removefromimage #whitebackgroundremove #photocutout #imageediting #photomanipulation

    ReplyDelete
  11. I am very enthusiastic when I read your articles. Please keep sharing more and more wonderful articles.

    ReplyDelete
  12. Great Job Here! I read a lot of blog posts and I never heard of a topic like this. I like this topic you made about structural engineer sydney. Very ingenious.

    ReplyDelete

Post a Comment

Popular posts from this blog

What is Java Class and Object?

Python Behave Tutorial: A Comprehensive Guide to Behavior-Driven Development (BDD)

What Role Graphic Design Services Play in Marketing

Automation Practice: Automate Amazon like E-Commerce Website with Selenium

17 Best Demo Websites for Automation Testing Practice

Mastering Selenium Practice: Automating Web Tables with Demo Examples

Top Free YouTube Download Apps: Download YouTube Videos Software Free

Top 10 Highly Paid Indian CEOs in the USA

14 Best Selenium Practice Exercises for Automation Practice