Browser Commands in Selenium WebDriver for Beginners

Selenium WebDriver is widely used for automating web browsers. Whether you're testing a web application or simulating user interactions, browser commands are essential for controlling the browser. In this guide, we’ll cover key browser commands in Selenium WebDriver, focusing on simplicity and clarity for beginners.

Browser commands provide precise control over browser actions, such as loading specific pages, retrieving information like page titles and URLs, accessing page source code, and managing browser windows. They facilitate interaction with web applications, making it easier to perform automation and scrape data from web pages.

Common Browser Commands include:

  1. get()
  2. getTitle()
  3. getCurrentUrl()
  4. getPageSource()
  5. close()
  6. quit()

1. Launching a Browser

To start automation, you need to open a browser. Selenium WebDriver supports multiple browsers like Chrome, Firefox, and Edge. Here's how you can launch a browser.

Example:

Java

WebDriver driver = new ChromeDriver();  // Opens Chrome browser

Explanation of Code

  1. WebDriver driver: This declares a variable driver of type WebDriver. This variable will be used to control the browser during test automation.
  2. = new ChromeDriver(): This part of the statement creates a new instance of the ChromeDriver class. The new keyword is used to allocate memory for the ChromeDriver object.
  3. Result: After execution, the driver variable is linked to a Chrome browser instance. This allows interaction with the browser using methods defined in the WebDriver interface, enabling navigation to web pages, locating elements, and executing various actions.

2. Opening a Webpage

Command: get(String url): void
Usage: Opens the specified URL in the browser, accepting a string parameter that specifies the URL of the page to open.

Example:

Java

driver.get("http://example.com");  // Opens a webpage
     
   

Explanation of Code

  • driver: This variable represents the instance of the WebDriver that controls the browser.
  • .get("http://example.com"): This method call instructs the browser to navigate to the specified URL, which is "http://example.com".
  • Result: After executing this command, the browser will load the specified page, allowing further interactions and operations to be performed on the elements of that webpage.

3. Getting the Page Title

Command: getTitle(): String
Usage: Retrieves the title of the currently displayed web page in the browser. Returns the title as a string.

Example:

Java

String title = driver.getTitle();  // Retrieves the title
     
   

Explanation of Code

  • String title: This declares a variable named title that will store the title of the web page as a string.
  • =: This is the assignment operator used to assign the value obtained from the getTitle() method to the title variable.
  • driver.getTitle(): This method call retrieves the title of the currently active web page in the browser.
  • Once executed, title will contain the name of the webpage currently being displayed, which can be used for verification or logging purposes.

4. Getting the Current URL

Command: getCurrentUrl(): String
Usage: Fetches the URL of the current web page shown in the browser. Returns the URL as a string.

Example:

Java

String currentUrl = driver.getCurrentUrl();  // Retrieves the URL
     
   

Explanation of Code

  • String currentUrl: This declares a variable named currentUrl that will store the URL of the web page as a string.
  • =: This is the assignment operator used to assign the value obtained from the getCurrentUrl() method to the currentUrl variable.
  • driver.getCurrentUrl(): This method call retrieves the URL of the currently active web page in the browser.
  • After execution, currentUrl will contain the address of the web page currently displayed, which can be useful for logging, testing, or verification purposes.

5. Getting the Page Source

Command: getPageSource(): String
Usage: Obtains the entire page source of the currently loaded web page. Returns the page HTML source code as a string.

Example:

Java

String pageSource = driver.getPageSource();  // Gets the page source
     
   

6. Closing the Browser

Command: close(): void
Usage: Closes the current browser window or tab. This command does not accept parameters and does not return any values.

Example:

Java

driver.close();  // Closes the current window
     
   

Explanation of Code

  • driver.close();: This command closes the current browser window that the WebDriver is controlling.
  • Result: After executing driver.close();, the current browser window will be closed. If there are other windows open, the WebDriver session remains active.
  • This method is useful when you want to close a specific window or tab without ending the entire WebDriver session.

7. Quitting the Browser

Command: quit(): void
Usage: Closes all browser windows and tabs associated with the WebDriver session. This command does not accept parameters and does not return any values.

Example:

Java

driver.quit();  // Closes all browser windows
     
   

Explanation of Code

  • driver.quit();: This method is called on the driver instance to close all browser windows and end the WebDriver session.
  • Result: After executing driver.quit();, all browser windows opened by the WebDriver will be closed, and the session will be terminated. This ensures that no resources are left hanging after the test execution.
  • This method is essential for cleaning up and releasing resources after completing automation tasks.

Practical Exercises

Practice Exercise 1: Basic Browser Commands

Objective: Launch Chrome, navigate to a website, retrieve the title and URL, and close the browser.

Solution:

Java

package automationFramework;

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

public class WebDriverCommands {

    public static void main(String[] args) {
        
        String driverExecutablePath = "D:\\Drivers\\chromedriver.exe";
        System.setProperty("webdriver.chrome.driver", driverExecutablePath);
        WebDriver driver = new ChromeDriver(); 
        
        String url = "https://www.shop.demoqa.com"; 
        driver.get(url); 
        
        String title = driver.getTitle(); 
        int titleLength = title.length(); 
        
        System.out.println("Title of the page is: " + title); 
        System.out.println("Length of the title is: " + titleLength); 
        
        String actualUrl = driver.getCurrentUrl(); 
        if (actualUrl.equals(url)) { 
            System.out.println("Verification Successful - The correct URL is opened.");
        } else {
            System.out.println("Verification Failed - An incorrect URL is opened."); 
            System.out.println("Actual URL is: " + actualUrl); 
            System.out.println("Expected URL is: " + url);
        }
        
        String pageSource = driver.getPageSource(); 
        int pageSourceLength = pageSource.length(); 
        System.out.println("Total length of the Page Source is: " + pageSourceLength); 
        
        driver.close();
    }
}
     
   

Conclusion

Mastering these basic browser commands is the first step towards becoming proficient in Selenium WebDriver. They enable you to effectively control the browser for your automation tasks. As you progress, you can explore more advanced features and commands.

Related Interview Questions

  • How do you initialize a WebDriver instance? Provide an example.
  • What is the purpose of the get(String url) method in Selenium WebDriver?
  • How can you retrieve the title of a web page using Selenium WebDriver?
  • Describe how you can obtain the current URL of the page you are testing.
  • What is the difference between driver.close() and driver.quit()? When would you use each?
  • What is the purpose of the getPageSource() method, and when would you use it?