How to handle Dynamic Web Tables using Selenium WebDriver

 

In this blog we will discuss about automating dynamic web tables using Selenium WebDriver. Table is also a type of Web Element like checkbox, Radio Button, etc.

Table is a kind of web element, which is displayed, with the help of  tag in conjunction with the <tr> tag defines the row of the table and <th> tag tag for headings which defines heading of the table.

There are 2 types of HTML table

1. Static Table – Where number of rows and columns are fixed.
2. Dynamic Table – Where number of rows and columns are not fixed.

Below table is a Dynamic table. Based on input Assignee filter, the number of rows get altered. 

How to locate Web Table Elements

1) Open Chrome browser and go to – https://www.seleniumeasy.com/test/table-search-filter-demo.html

2) Take a note that “Element” tab is the one which displays all the HTML properties belonging to the current web page. Navigate to the “Element” tab if it is not opened by default on the launch.

3) In the screenshot, we can see the HTML code of Task web element of the table. Right click on this text and select Copy and then again click where will see options like – Copy Selector, Copy XPath, Copy full XPath.

Copy XPath
//*[@id="task-table"]/thead/tr/th[2]

Copy full XPath
/html/body/div[2]/div/div[2]/div[1]/div/table/thead/tr/th[2]

Copy Selector
#task-table > thead > tr > th:nth-child(2)

How to find full XPath of Web Table

If we divide this xpath  – /html/body/div[2]/div/div[2]/div[1]/div/table/thead/tr/th[2] into three different parts it will be like this

·         Part 1 – Location of the table in the webpage /html/body/div[2]/div/div[2]/div[1]/div />

·         Part 2 – Table body (data) starts from here

·         Part 3 – It says table row 1 and table head 2

In the below image, we can see that the highlighted tags are used to create absolute XPath – html/body/div[2]/div/div[2]/div[1]/div/table/thead/tr/th[2]

If we want to create a relative XPath, then the below image shows that find a unique identifier like id=’task-table’ and then create Relative XPath

//*[@id="task-table"]/thead/tr/th[2]

Below is an example, which will show how to fetch a particular cell data in Dynamic Web Table. We want to fetch the data from row 5 and column 3 and row 6  column 2. We have used Relative XPath as well as absolute XPath to fetch the data.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DynamicTable_RowData {
        public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();      
        driver.manage().window().maximize();
        driver.get("https://www.seleniumeasy.com/test/table-search-filter-demo.html");           
        
String CellData1 = driver.findElement(By.xpath("//*[@id='task-table']/tbody/tr[5]/td[3]")).getText();
        System.out.println("Data in 5th row and 3rd column :"+CellData1);

           String CellData2 = driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div[1]/div/table/tbody/tr[6]/td[2]")).getText();
        System.out.println("Data in 6th row and 2nd column :"+CellData2);
        driver.close();
        }
}

Output
Data in 5th row and 3rd column :Holden Charles
Data in 6th row and 2nd column :Browser Issues

How to create first Selenium WebDriver Script using Java

We assume here that Selenium WebDriver is download and installed with Eclipse. If not, please refer this link

In this tutorial, we will see how to create a simple Selenium WebDriver script using JAVA. The most important thing is that JAVA, Eclipse and Selenium WebDriver are already install in the machine. If not, then please refer the link – How to Download & Install Selenium WebDriver.

To create our first Selenium WebDriver Script, we have to create a Java Project, Package and Class in Eclipse.

1. Create a Java Project “AutomationSuite” – Click File ->New ->Other ->Project ->Java Project. Click Next.

  • Provide Package Name – here I have provided AutomationSuite 
  • JRE – Use an execution environment JRE: JavaSE-1.8 (This is the version of Java on your machine)
  • Project Layout – Create separate folders for source and class files

ii. Create a package “SeleniumTutorial” – Right click Java Project (AutomationSuite) ->Click File ->New ->Package

iii. Create a Java Class “FirstProgram” – Right click Java Package (SeleniumTutorial) ->Click File ->New ->Class

  • Name: Name of the class (FirstProgram)
  • Modifiers – Public
  • Which method stubs would you like to create – public static void main(String[] args) and click Finish

Above displayed image explains the structure of Project in Eclipse.

Add Selenium Jar files to the Java Project


1.  Right click on AutomationSuite and click on Properties.

2.  Click on Java Build Path. Select Libraries. Click on – Add External JARs

3.  Go to the path where Selenium WebDriver JAR folder was downloaded and select 2 JAR files – client-combined-3.141.59 and client-combined-3.141.59-sources and click on Open button.

4. Similarly, go to Lib folder of Selenium file and select the entire JAR present there

5. To verify that the JAR’s are added or not, click on Referenced Libraries and will see all these JARs are present here. For more details, refer the link

Scenario:


To open appropriate URL and verify the title of the home page
Steps:
i. Open Chrome browser
ii. Go to the specified URL – http://www.google.com
iii. Verify the title and print the output of the title
iv. Close the Chrome browser

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class FirstProgram {
       
     public static void main(String[] args) {
               
 System.setProperty("webdriver.chrome.driver","C:\\Users\\vibha\\Downloads\\Drivers\\chromedriver_win32\\chromedriver.exe"");

         WebDriver driver = new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
         driver.get("https://www.google.com/");
         String PageTiltle = driver.getTitle();
         System.out.println("Page Title :"+PageTiltle);
         driver.close();
     }
}

To run this program, go to Run->Run or Green Icon shown below

How to get all options in a DropDown list in Selenium WebDriver

 
 

In this tutorial, we will get to know how we can get the option values of a dropdown using Webdriver. This can be done by using getOptions().

getOptions( ) : List – It shows all options belonging to the Select tag. It takes no parameter and returns List.

oSelect.getOptions();

Below is an example on how to use getOptions. We want to print all the options of Drop Down Month.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class DropDown_Options {
      public static void main(String[] args) {
         System.setProperty(“webdriver.gecko.driver”,“C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe”);
            FirefoxDriver driver = new FirefoxDriver();
                  
            driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
            driver.get("https://www.facebook.com/";);          
            
Select mselect = new Select(driver.findElement(By.id(“month”)));       
            
            // Print all the options for the selected drop down and select one option of your choice
            // Get the size of the Select element
            List mSize = mselect.getOptions();
            int OptionSize = mSize.size();                                   
           
            // Setting up the loop to print all the options
            for(int i =0; i < OptionSize ; i++)
          {
           
          // Storing the value of the option
           String Options = mselect.getOptions().get(i).getText();
           
          // Printing the stored value
           System.out.println(Options);
        }
   }
}

Output
Month
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

How to automate selecting Checkbox and Radio Buttons in Selenium WebDriver

 
 

In this tutorial, we will see how to identify the form elements like CheckBox and Radio Button

Toggling a CheckBox or Radio Button on/off is also done using the click() method.

IsSelected – IsSelected method, let us know that the element selected or not. Assume there are two Radio Buttons/Check Boxes, one selected by default and you want to select the other one for your test. Then, we use IsSelected method. When there is a group of Radio Buttons/Check Boxes on the page then, most probably, their names are same, but values are different. Then we use the Webdriver findElements command to get the list of web elements.

Below is the working example of CheckBox.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class Checkbox_Test {
     
      public static void main(String[] args) {
            System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver = new ChromeDriver();
          driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
          driver.get("https://www.seleniumeasy.com/test/basic-checkbox-demo.html");
 
           //Single option selection
           System.out.println("*******Single option selection *********");
           driver.findElement(By.id("isAgeSelected")).click();
           String Message = driver.findElement(By.id("txtAge")).getText();
           System.out.println("Message is :"+Message);    
 
       // close the web browser
        driver.close();   
    }
}

Output
*******Single option selection *********
Message is :Success - Check box is checked

How to click all options in the Checkbox

In the below image, there are 4 checkboxes. Initially, when checkboxes were not selected, the test mentioned on the button is – Check All and once all the options are checked, the text on button changes to – Uncheck All.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public classCheckbox_Test {   
     
     public static voidmain(String[] args) throws Exception { 

 System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
          WebDriver driver = newChromeDriver();
          driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
          driver.get("https://www.seleniumeasy.com/test/basic-checkbox-demo.html");
 
          //Display the value of Button before clicking the options of checkbox
          String buttontext_beforeclick = driver.findElement(By.xpath(".//*[@id='check1']")).getAttribute("value");
          System.out.println("Text before click :"+buttontext_beforeclick);

          // Find the CheckBox by its classname
          List list = driver.findElements(By.xpath("//input[@type ='checkbox' and @class='cb1-element']") );            
             
          // Get the number of CheckBoxes available
          int CheckBox_Size = list.size();
          System.out.println("Number of Checkbox options :"+CheckBox_Size);             
            
          // Iterate the loop from first CheckBox to last Checkbox
          for(int i=0;i<CheckBox_Size;i++)
          {     
                list.get(i).click();               
           }
          String buttontext_afterclick = driver.findElement(By.xpath(".//*[@id='check1']")).getAttribute("value");
          System.out.println("Text after click :"+buttontext_afterclick); 
    driver.quit();      
     }
}

Output
Text before click :Check All
Number of Checkbox options :4
Text after click :Uncheck All

Similarly, below I have explained Radio Button.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
 public class Radio_Test {

       public static void main(String[] args) {      
 
     System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");

          FirefoxDriver driver = new FirefoxDriver();
          driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
          driver.get("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html");

          List<WebElement> Radio_Options = driver.findElements(By.name("optradio"));    
  
          // Create a boolean variable which will hold the value (True/False)
          boolean radio_value = false;

          // This statement will return True, in case of first Radio button is selected
         radio_value = Radio_Options.get(0).isSelected();

         //Identify if Radio Button 1 is selected or not. If Button 1 is already selected, then select Button 2
         if(radio_value==true)
         {
              Radio_Options.get(1).click();
              System.out.println("Button Selected is :"+ Radio_Options.get(1).getAttribute("value"));  
         }
         else
         {
               Radio_Options.get(0).click();
               System.out.println("Button Selected is :"+ Radio_Options.get(0).getAttribute("value"));  
          }

          driver.findElement(By.id("buttoncheck")).click();
          String Button_Selected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]")).getText();
          System.out.println("Get Checked Value is :"+ Button_Selected); 
       
         //Group Radio Button Selection
         driver.findElement(By.xpath(".//input[@name='gender'and @value='Female']")).click();
         driver.findElement(By.xpath(".//input[@name='ageGroup' and @value='15 - 50']")).click();
         driver.findElement(By.xpath(".//*[@id='easycont']/div/div[2]/div[2]/div[2]/button")).click();
          String Group_Radio_Message = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[2]/div[2]/p[2]")).getText();

          System.out.println("Get Values are :"+Group_Radio_Message);

         // close the web browser
        driver.close();
      }
}
 
Output
Button Selected is :Male
Get Checked Value is :Radio button 'Male' is checked
Get Values are :Sex : Female
Age group: 15 - 50

Selenium Form WebElement Commands – Sendkeys, Clear, Click, Submit

HOME

WebElement represents HTML DOM(Document Object Model) element. Anything present on web page like alert box, text box, button- all are WebElements.  When HTML loads into a web browser, it is convert into document object

WebElement in Selenium is a generic class that converts object into document object. There are a number of WebElement commands present in Selenium, but in this blog will discuss about

1) sendKeys()
2) clear()
3) Submit()
4) click()

1) SendKeys – This simulate typing into an element, which may set its value. This method accepts CharSequence as a parameter and returns nothing.

This method works fine with text entry elements like INPUT and TEXTAREA elements.

Input boxes refer to either of these two types: 
1. Text Fields– text boxes that accept typed values and show them as they are.
2. Password Fields– text boxes that accept typed values but mask them as a series of special characters (commonly dots and asterisks) to avoid sensitive values to be displayed.

To enter text into the Text Fields and Password Fields, sendKeys() is the method available on the WebElement. 

Syntax:

sendKeys(CharSequence… keysToSend ) : void

Command:

driver.findElement(By.xpath("//*[@name = 'email']")).sendKeys("abc123@gmail.com") 

2) Clear – If this element is a text entry element, this will clear the value. This command does not require any parameter and return nothing.

Syntax:

clear( ) : void 

Command:

email.clear(); 

3) Submit – This method works well/better than the click(), if the current element is a form, or an element within a form. This command does not require any parameter and return nothing.

Syntax:

submit():void

Command:

driver.findElement(By.id("u_0_2")).submit(); 

4) Click – This simulates the clicking of any element. This command does not require any parameter and return nothing. 

The buttons can be accessed using the click() method.

Syntax:

click():void 

Command:

driver.findElement(By.id("u_0_2")).click(); 

Let us write a small program to see the use of these commands. I have used both click() and submit commands() to show how they work, but when you try to run this program, comment any one of the part.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class Facebook_Login {
       public static void main(String[] args) {
              System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
             
           // Create a new instance of the Firefox driver
           WebDriver driver = new FirefoxDriver();
 
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
           driver.get("https://www.facebook.com/");
           driver.manage().window().maximize();
           WebElement email = driver.findElement(By.xpath("//*[@name = 'email']"));
           WebElement password = driver.findElement(By.xpath("//*[@name = 'pass']"));
           Thread.sleep(1000);
 
          // switch from main window to child window
           for (String handle1 : driver.getWindowHandles()) {
                    driver.switchTo().window(handle1);
           }
 
           driver.findElement(By.id("u_0_k")).click();
 
           // Enter data in Text box
           email.sendKeys("abc123@gmail.com");
           password.sendKeys("Abc123@");
           System.out.println("Data is entered in Text Field");
 
           // Delete values from text box
           email.clear();
           password.clear();
           System.out.println("Data is cleared from Text Field");
 
           // Using submit method to submit the form
           email.sendKeys("abc123@gmail.com");
           password.sendKeys("Abc123@");
           driver.findElement(By.id("u_0_2")).submit();
           System.out.println("Login Done with Submit");
      }
}
      
Output:
Data is entered in Text Field
Data is cleared from Text Field
Login Done with Submit  

Difference between FindElement and FindElements in Selenium WebDriver

 

Identifying the web elements in a page is required to interact with the web page. Selenium WebDriver give us FindElement and FindElements methods to locate elements on the webpage. There are multiple ways to identify uniquely a web element within the web page such as ID, Name, Class Name, LinkText, PartialLinkText, TagName, and XPath.

FindElement Command

This method locates the first web element on the current web page matching the criteria mentioned as parameters.  

If the web element is not found, it will throw an exception – NoSuchElementException.

Syntax:

findElement(By arg0):WebElement - WebDriver

Command:

driver.findElement(By.xpath("Xpath location"));

How to use FindElement in Selenium

The following application is used for demo purposes:

https://www.facebook.com/

Scenario – Valid

  •      Open the web page
  •      Close the child window and move to facebook main page
  •      Enter the emailId and password and click on Log In Button
import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver;
public class FindElement_Example { 
        
         public static voidmain(String[] args){
           System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");

         // Create a new instance of the Firefox driver
          WebDriver driver = new FirefoxDriver();
          
        // Set implicit wait of 60 sec for managing waits in selenium webdriver
         driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
                       
        // Launch a new web page and load Facebook
         driver.get("https://www.facebook.com/");
         Thread.sleep(1000); 
            
        //switch from main window to child window
        for (String handle1 : driver.getWindowHandles()) {
               driver.switchTo().window(handle1);
         }
         driver.findElement(By.id("u_0_k")).click();

         // Enter the values in Email and Password Textboxes
         driver.findElement(By.name("email")).sendKeys("abc@gmail.com");
         driver.findElement(By.id("pass")).sendKeys("abcd1234!"); 
               
         // Click on Log In Button
         driver.findElement(By.id("u_0_b")).click();
         driver.close();
    }
}

Scenario – Error

  •      Open the web page
  •      Close the child window and move to facebook main page
  •      Use incorrect locator to find emailId
  •      Execution halts and then stopped with NoSuchElementException
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElement_Example {
        
         public static void main(String[] args){
           System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
    
         // Create a new instance of the Firefox driver
          WebDriver driver = new FirefoxDriver();
                        
         // Set implicit wait of 60 sec for managing waits in selenium webdriver
         driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

         // Launch a new web page and load Facebook
         driver.get("https://www.facebook.com/");
         Thread.sleep(1000);    
         
         //switch from main window to child window
         for (String handle1 : driver.getWindowHandles()) {
                 driver.switchTo().window(handle1);
          }
          driver.findElement(By.id("u_0_k")).click();

         // Enter the values in Email and Password Textboxes
          driver.findElement(By.name("email")).sendKeys("abc@gmail.com");
          driver.findElement(By.id("pass")).sendKeys("abcd1234!"); 
               
          // Click on Log In Button
          driver.findElement(By.id("u_0_b")).click();
          driver.close();
      }
}

FindElements Command

  • This method locates all the web elements on the current web page matching the criteria mentioned as parameter.  
  • If not found any WebElement on current page as per given element locator mechanism, it will return empty list.                                                                                    

Syntax

findElements (By arg0):List

Below is the example of findElements

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElements_Example {
       public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
            // Create a new instance of the Firefox driver
             WebDriver driver = new FirefoxDriver();

             // Set implicit wait of 60 sec for managing waits in selenium webdriver
             driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

             // Launch a new web page and load Facebook
             driver.get("https://www.facebook.com/");
             Thread.sleep(1000);

             // switch from main window to child window
             for (String handle1 : driver.getWindowHandles()) {
                    driver.switchTo().window(handle1);
             }
             driver.findElement(By.id("u_0_k")).click();
             driver.findElement(By.xpath("//*[@id='u_0_2']")).click();

             // Find all elements and store into list
              List Link_List = driver.findElements(By.id("month"));
              for (WebElement link : Link_List)

              // Print all the elements from the list
              System.out.println(link.getText());
               driver.close();
        }
}

Output
Month
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

Differences between findElement() and findElements() method:

·         Return type of findElement() is a WebElement (single) while Return type of findElements() is a List (multiple).

·         findElement() method will throw noSuchElementException if web element is not found in WebPage while findElements() will return an empty list and do not throw any.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

WebDriver Browser Commands – get, getTitle, getCurrentUrl, getPageSource, getClass, close, quit in Selenium WebDriver

WebDriver is a tool for automating web application testing, and in particular, to verify that they work as expected. WebDriver is design to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API. Selenium-WebDriver was develop to better support dynamic web pages where elements of a page may change without the page itself being reload. WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems. 

In this tutorial, we are discussing about below mentioned topics:-
1) How to access the methods of WebDriver?
2) Various Browser Commands

  • get()
  • getTitle()
  • getCurrentUrl()
  • getPageSource()
  • getClass()
  • close()
  • quit()

How to access the methods of WebDriver?

To access a method of WebDriver, you need to create a driver object from WebDriver and press. dot key. This will list all the methods. Here, you can see that I have used driver.get, so it will show all the methods starts with get.

Method Name – I have explained earlier about Method. A method is a block of code that is use to perform certain actions. Method runs when it is call. Method name is the name of method we are going to use. 

Parameter Data Type – It is pass as an argument to the method to perform certain operation. Here, string data type is use as an argument. 

Return Type – Methods can return values like getTitle() : String as string is here the return type. In the above example, return type is void means do not return anything.

Browser Commands

1) Get – This command loads a new web page in the current browser window and open the webpage mentioned as argument. It accepts string as parameter and void means returns nothing. 

Syntax

get(String arg0) : void    

Command

Command - driver.get(URL) 

2) Get Title – This command retrieves the title of current web page. It does not accept any parameter and returns a string value. 

Syntax

getTitle() : String   

Command

driver.getTitle()

3) Get Current URL – This command retrieves the URL of current web page. It does not accept any parameter and returns a string value.

Syntax

getCurrentUrl() : String  

Command

driver.getCurrentUrl(); 

4) Get Page Source – This command returns the page source of current web page. . It does not accept any parameter and returns a string value.

Syntax

getPageSource() : String  

Command

driver.getPageSource();

5) Get Class – The command is use to retrieve the Class object that represents the runtime class of this object.

Syntax

getClass() 

Command

driver.getClass(); 

6) Close – This command is use to close the current web browser, which is controlled by WebDriver. This command does not require any parameter and void means return nothing.

Syntax

close(): void 

Command

driver.close()

7) Quit – This command close all the browsers opened by webDriver. This command does not require any parameter and void means return nothing.

Syntax

quit(): void 

Command

driver.quit(); 

Now, let us write a small program to show the use of methods of WebDriver.  

  1. Launch a new Firefox browser
  2. Open facebook.com
  3. Get Page Title name and print
  4. Get Page URL and print on Eclipse Console
  5. Get Page Source (HTML Source code) and Page Source length and print Page length
  6. Get Runtime class name of the object
  7. Close the Browser
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Selenium_Browser_Commands {
    public static void main(String[] args) throws {
         System.setProperty("webdriver.gecko.driver",
                                              "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\geckodriver-v0.27.0-win64\\geckodriver.exe");
 
             // Create a new instance of the Firefox driver 
             WebDriver driver = new FirefoxDriver();
             driver.manage().window().maximize();
 
            // Set implicit wait of 60 seconds
             driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
 
            // Launch a new web page and load Facebook using Get Command
             driver.get("https://www.facebook.com/");
 
             // Get the Title of web page
             String PageTitle = driver.getTitle();
             System.out.println("Title of page is :"+ PageTitle);
 
             // Get URL of current web page
             String PageURL = driver.getCurrentUrl();
             System.out.println("URL of current page is :" + PageURL);
 
             // Get Source code of current web page
             String PageSource = driver.getPageSource();
             int PageSource_Length = PageSource.length();
             System.out.println("Length of page source of current page is :" + PageSource_Length);
 
              // Get Runtime class of this object
              Class<? extends WebDriver> className = driver.getClass();
              System.out.println("className :" + className);
 
              // Close the current web page
              driver.close();
        } 
}

Output
Title of page is :Facebook – log in or sign up
URL of current page is :https://www.facebook.com/
Length of page source of current page is :293624
className :class org.openqa.selenium.firefox.FirefoxDriver