How to find duplicate contents on website or web page in Selenium Webdriver using java

Duplicate content is content that appears on the website or web page in more than one URL same title. When create one more web page with same title under same content type in famous CMS like Drupal, Joomla and WordPress etc then created pages with same title but pages url are different. For example i create three basic page with title 'About QA' in drupal CMS and created three urls are 'http://localhost/duplicatexontent/about-qa', 'http://localhost/duplicatexontent/about-qa-0' and http://localhost/duplicatexontent/about-qa-1. Sometime migrate one website data like as pages, orders, product to other website by script and create duplicate content. Now I show how to find duplicate content in this tutorial using Selenium Webdriver.


Demo Duplicate Content HTML Page Code
 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>duplicte</title>  
 </head>  
 <body>  
 <div align="center">  
 <table border="1">  
  <thead>   
   <tr>   
       <th>Title</th>   
       <th>Type</th>  
        <th>Author</th>  
      </tr>  
  </thead>  
  <tbody>   
   <tr>  
       <td><a href="http://localhost/duplicatexontent/about-qa">About QA</a> </td>  
       <td>Basic page</td>  
        <td>hiro</td>  
      </tr>   
       <tr>  
        <td><a href="http://localhost/duplicatexontent/about-qa-1">About QA</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td><a href="http://localhost/duplicatexontent/code-runner">Code Runner</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td> <a href="http://localhost/duplicatexontent/access-denied">ACCESS DENIED</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td><a href="http://localhost/duplicatexontent/circulation">Circulation</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>   
       <tr>  
        <td><a href="http://localhost/duplicatexontent/digital-advertising">Digital Advertising</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td><a href="http://localhost/duplicatexontent/summary-body">Summary of Body</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td> <a href="http://localhost/duplicatexontent/webinars">Webinars</a></td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td><a href="http://localhost/duplicatexontent/videos">Videos</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td> <a href="http://localhost/duplicatexontent/resources">Resources</a></td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>        
       <tr>  
        <td> <a href="http://localhost/duplicatexontent/news">News</a></td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>  
   <tr>  
        <td><a href="http://localhost/duplicatexontent/about-qa-10">About QA</a> </td>  
        <td>Basic page</td>  
        <td>hiro</td>  
       </tr>         
  </tbody>  
 </table>  
 </div>  
 </body>  
 </html>  

HTML page Output


Demo Selenium Webdriver Code for Upper Duplicate Contents Html page
 import java.util.ArrayList;  
 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;  
 import org.openqa.selenium.NoSuchElementException;

  
 public class Duplicatecontentshandler {  
   public static void main(String[] args) throws InterruptedException {  
     List<String> freshcontents, duplicatecontents;  
     freshcontents = new ArrayList();  
     duplicatecontents = new ArrayList();  
     List<WebElement> urllist;  
     try {  
       WebDriver driver = new FirefoxDriver();  
       driver.manage().window().maximize();  
       driver.get("file:///C:/Users/Hiro%20Mia/Desktop/Blog%20content/duplicate%20contents.html");  
       driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
       urllist = driver.findElements(By.tagName("a"));  
       for (WebElement url : urllist) {  
         // check duplicate content  
         if (url.getAttribute("href").trim().matches("([^\\s]+(\\-[0-9])$)")) {  
           //store duplicate contents into duplicatecontents List variable  
           duplicatecontents.add(url.getText().trim() + "  " + url.getAttribute("href").trim());  
         } else {  
           //store Fresh content into freshcontents List variable  
           freshcontents.add(url.getText().trim() + "  " + url.getAttribute("href").trim());  
         }  
       }  
       driver.quit();  
     } catch (NoSuchElementException e) {  
       e.printStackTrace();  
     }  
     System.out.println("===== Duplicate contents =======");  
     System.out.println("Number of duplicate contents =: " + duplicatecontents.size());  
     for (String duplicate : duplicatecontents) {  
       System.out.println(duplicate);  
     }  
     System.out.println("\n===== Fresh contents =======");  
     System.out.println("Number of Fresh contents =: " + freshcontents.size());  
     for (String fresh : freshcontents) {  
       System.out.println(fresh);  
     }  
   }  
 }  

Output
 ===== Duplicate contents =======  
 Number of duplicate contents =: 2  
 About QA  http://localhost/duplicatexontent/about-qa-1  
 About QA  http://localhost/duplicatexontent/about-qa-10  
 ===== Fresh contents =======  
 Number of Fresh contents =: 10  
 About QA  http://localhost/duplicatexontent/about-qa  
 Code Runner  http://localhost/duplicatexontent/code-runner  
 ACCESS DENIED  http://localhost/duplicatexontent/access-denied  
 Circulation  http://localhost/duplicatexontent/circulation  
 Digital Advertising  http://localhost/duplicatexontent/digital-advertising  
 Summary of Body  http://localhost/duplicatexontent/summary-body  
 Webinars  http://localhost/duplicatexontent/webinars  
 Videos  http://localhost/duplicatexontent/videos  
 Resources  http://localhost/duplicatexontent/resources  
 News  http://localhost/duplicatexontent/news  

How to use String operations like as compare, replace, search and split string etc in Selenium Webdriver

Common programming tasks like as compares the two given strings, searches the sequence of characters in this string, eliminates leading and trailing spaces, length of the string, a string replacing all the old char or CharSequence to new char or CharSequence, converts all characters of the string into lower to upper, upper to lower case letter etc and in Java has special String class that provides several methods to handle those type of operation. We can use String methods in selenium webdriver to operate these type tasks. This tutorial I will see how to use these String methods in selenium webdriver.


Method name: trim
Syntax : public String trim()
Purpose : Return string with omitted leading and trailing spaces

Method name: contains
Syntax : public boolean contains(CharSequence sequence)
Purpose : searches the sequence of characters in this string. It returns true if sequence of char values are found in this string otherwise returns false.

Method name: format
Syntax : public static String format(String format, Object... args) )
Purpose : returns the formatted string by given locale, format and arguments.

Method name: startsWith
Syntax : public boolean startsWith(String Sequence_of_character)
Purpose : checks if this string starts with given Sequence of character. It returns true if this string starts with given Sequence of character else returns false.

Method name: endsWith
Syntax : public boolean endsWith(String Sequence_of_character)
Purpose : checks if this string ends with given Sequence of character. It returns true if this string ends with given Sequence of character else returns false.

Method name: equals and equalsIgnoreCase
Syntax : public boolean equals(Object anotherObject) or public boolean equalsIgnoreCase(Object anotherObject
Purpose : compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. equals method is case sensitive and equalsIgnoreCase is not case sensitive.

Method name: isEmpty
Syntax : public boolean isEmpty()
Purpose : checks if this string is empty. It returns true, if length of string is 0 otherwise false.

Method name: length or size
Syntax : public int length() or public int size()
Purpose : length of the string. It returns count of total number of characters.

Method name: replace
Syntax : public String replace(char oldChar, char newChar)
Purpose : returns a string replacing all the old char or CharSequence to new char or CharSequence.

Method name: split
Syntax : public String split(String regex)
Purpose : splits this string against given regular expression and returns a char array

Method name: toLowerCase
Syntax : public String toLowerCase()
Purpose : returns the string in lowercase letter. In other words, it converts all characters of the string into lower case letter.

Method name: toUpperCase
Syntax : public String toUpperCase()
Purpose : returns the string in uppercase letter. In other words, it converts all characters of the string into upper case letter.

Demo Java Source Code
 public class Stringmethodshandler {  
   public static void main(String[] args) {  
     String str_normal, str_equals, stra[];  
     double formatnumer = 125.58655;  
     str_normal = " Welcome to Java Demo Program ";  
     str_equals = "Selenium Webdriver";  
     // trim method example  
     System.out.println("Befor Trim =: " + str_normal);  
     System.out.println("After Trim =: " + str_normal.trim());  
     // contains method example  
     if (str_normal.contains("Demo")) {  
       System.out.println("contains method pass");  
     } else {  
       System.out.println("contains method fail");  
     }  
     // startsWith method example  
     if (str_normal.trim().startsWith("Welc")) {  
       System.out.println("startsWith method pass");  
     } else {  
       System.out.println("startsWith method fail");  
     }  
     // endsWith method example  
     if (str_normal.trim().endsWith("ogram")) {  
       System.out.println("endsWith method pass");  
     } else {  
       System.out.println("endsWith method fail");  
     }  
     // isEmpty method example  
     if (str_normal.isEmpty()) {  
       System.out.println("isEmpty method pass");  
     } else {  
       System.out.println("isEmpty method fail");  
     }  
     // equals method example  
     if (str_equals.equals("Selenium webdriver")) {  
       System.out.println("equals method pass");  
     } else {  
       System.out.println("equals method fail");  
     }  
     // equalsIgnoreCase method example  
     if (str_equals.equalsIgnoreCase("Selenium webdriver")) {  
       System.out.println("equalsIgnoreCase method pass");  
     } else {  
       System.out.println("equalsIgnoreCase method fail");  
     }  
     // length method example      
     System.out.println("String length =: " + str_normal.length());  
     // replace method example  
     System.out.println("String replaced =: " + str_normal.trim().replace("Demo", "Example"));  
     // format method example  
     System.out.println("Format method examplet =: " + String.format("%.2f", formatnumer));  
     // toLowerCase method example  
     System.out.println("toLowerCase method example =: " + str_equals.toLowerCase());  
     // toUpperCase method example  
     System.out.println("toUpperCase method example =: " + str_equals.toUpperCase());  
     // split method example  
     System.out.println("============================================================");  
     stra = str_normal.trim().split(" ");  
     for (int i = 0; i < stra.length; i++) {  
       System.out.println("splited string =: " + i + " " + stra[i]);  
     }  
   }  
 }  

Output
 Befor Trim =:  Welcome to Java Demo Program   
 After Trim =: Welcome to Java Demo Program  
 contains method pass  
 startsWith method pass  
 endsWith method pass  
 isEmpty method fail  
 equals method fail  
 equalsIgnoreCase method pass  
 String length =: 30  
 String replaced =: Welcome to Java Example Program  
 Format method examplet =: 125.59  
 toLowerCase method example =: selenium webdriver  
 toUpperCase method example =: SELENIUM WEBDRIVER  
 ============================================================  
 splited string =: 0 Welcome  
 splited string =: 1 to  
 splited string =: 2 Java  
 splited string =: 3 Demo  
 splited string =: 4 Program  


Selenium Webdriver Demo Source Code
 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;  
 import org.openqa.selenium.support.ui.Select;  
 public class SeleStringmethodshandler {  
   public static void main(String[] args) throws InterruptedException {  
     String selected_country_name, link_signup, strspilt[];  
     // create objects and variables instantiation     
     WebDriver driver = new FirefoxDriver();  
     // maximize the browser window     
     driver.manage().window().maximize();  
     // launch the firefox browser and open the application url    
     driver.get("http://www.gmail.com/");  
     //Set timeout     
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // trim, equalsIgnoreCase method example   
     Select countres = new Select(driver.findElement(By.id("lang-chooser")));  
     selected_country_name = countres.getFirstSelectedOption().getText();  
     System.out.println("Selected country name =: " + selected_country_name);  
     if (!(selected_country_name.trim().equalsIgnoreCase("English (United States)"))) {  
       countres.selectByValue("en");  
     }  
     // size method example  
     for (int i = 0; i < countres.getOptions().size(); i++) {  
       System.out.println("Country name =: " + i + " " + countres.getOptions().get(i).getText().trim());  
     }  
     // contains method example  
     if (driver.getPageSource().contains("Gmail")) {  
       System.out.println("Gmail is contain in www.gmail.com");  
     } else {  
       System.out.println("Gmail is not contain in www.gmail.com");  
     }  
     link_signup = driver.findElement(By.id("link-signup")).getText().trim();  
     // startsWith method example  
     if (link_signup.startsWith("Create")) {  
       System.out.println("startsWith method pass");  
     }  
     // endsWith method example   
     if (link_signup.endsWith("account")) {  
       System.out.println("endsWith method pass");  
     }  
     // isEmpty method example  
     if (!(link_signup.isEmpty())) {  
       System.out.println("isEmpty method pass");  
     }  
     // equals method example  
     if (link_signup.equals("Create account")) {  
       System.out.println("equals method pass");  
     }  
     // toUpperCase method example   
     System.out.println("toUpperCase method example =: " + link_signup.toUpperCase());  
     // toLowerCase method example  
     System.out.println("toLowerCase method example =: " + link_signup.toLowerCase());  
     // split method example  
     strspilt = link_signup.split(" ");  
     for (int i = 0; i < strspilt.length; i++) {  
       System.out.println(strspilt[i]);  
     }  
     // quit Firefox browser    
     driver.quit();  
   }  
 }  

How to use CSS selector to identifying web elements in Selenium Webdriver using java

CSS selector:

When there is no an option to choose web element using selector like as ID or Name etc, Selenium Webdriver prefer to use CSS locators as the best alternative to choose web element. CSS Selector is combination of an element selector and a selector value which identifies the web element within a web page. Selector Pattern is made using HTML tags, attributes and their values. CSS locators is Advantage, faster and simpler than Xpath.
Some important terms for CSS selectors
HTML tag - It is tag. HTML tags are the hidden keywords within a web page that help to define how the browser must format and display the content. In Selenium Webdriver it help to access web element which we want.
Attribute – An attribute defines a property for an web element, consists of an attribute/value pair, and appears within the opening tag. It is the attribute we want to use to create CSS Selector.
Value of attribute – It is the value of an attribute which is being access
# – The hash(#) character is used to indicate ID attribute. It is mandatory to use hash sign for ID attribute in CSS Selector.
Value of ID attribute – It is the value of an ID attribute which want to access.

. – The dot(.) character is used to introduce Class attribute in CSS locator. It is mandatory to use dot sign before class name if Class attribute is being used to create CSS Selector.
Value of ID attribute – It is the value of an ID attribute which want to access
^ – The hat(^) sign is used to match a string using prefix.
$ – The dollar($) symbol is used to match a string using suffix.
* –The symbol of asterisk(*) to match a string using sub string.
: – The dot(.) sign is used to match a string using contains method.

CSS Selector: ID
 <input id="email" type="email" tabindex="1" name="email">  
 <div id="rsi_card" class="card signin-card">  
Syntax : HTML tag_#_Value of ID attribute or HTML tag[Value of ID attribute]
Example :
WebElement idcssselector = driver.findElement(By.cssSelector("input#id=email"));
WebElement idcssselector = driver.findElement(By.cssSelector("input[id=email]"));
WebElement idcssselector = driver.findElement(By.cssSelector("div#id=rsi_card"));
WebElement idcssselector = driver.findElement(By.cssSelector("div[id=rsi_card]"));

CSS Selector: Class
 <input type="checkbox" class="uiInput" >  
 // For multiple classes  
 <input class="submit ipt second-ipt flex-table-ipt js-submit" type="email">  
Syntax : HTML tag_._Value of Class attribute
Example :
WebElement classcssselector = driver.findElement(By.cssSelector("input.uiInput"));
// For multiple classes
WebElement classcssselector1 = driver.findElement(By.cssSelector(".second-ipt"));
WebElement classcssselector2 = driver.findElement(By.cssSelector("ipt.second-ipt"));
WebElement classcssselector3 = driver.findElement(By.cssSelector("submit.second-ipt"));

CSS Selector: Attribute
 <input type="password" id="pass" name="pass">  
Syntax : HTML tag_[attribute=Value of attribute]
Example :
WebElement classcssselector = driver.findElement(By.cssSelector("input[name=pass][type=password]"));

CSS Selector: ID/Class and attribute
Syntax : HTML tag_. Or #_value of Class or ID attribute_[attribute=Value of attribute]
Example :

CSS Selector: Sub-string
Match a prefix
Syntax : HTML tag_[attribute^=prefix of the string]
Example :

Match a suffix
Syntax : HTML tag_[attribute$=suffix of the string]
Example :

Match a sub string
Syntax : HTML tag_[attribute*=sub string]
Example :


CSS Selector: Inner text
Syntax : HTML tag_:_contains_(text)
Example :

Demo Source Code

How to operate hidden or invisible web elements in Selenium Webdriver using Java

Sometime We need to handle invisible or hidden web elements but Selenium WebDriver will only interact with visible elements, therefore the text of an invisible element will always be returned as an empty string. In some cases We need to operate like as click, get text, send value etc hidden web elements. The follow attribute use to hide web element.

style="Display:none;"

 <div class="owl-prev" style="display: none;">prev</div>  

style="Display:block;"

 <div data-easeout="bounceOutLeft" data-easein="bounceInRight" data-stop="7800" data-start="300" data-height="26" data-width="184" data-y="155" data-x="183" class="md-object md-layer-1-0-0 bounceInRight" style="width: 9.58333%; height: 5.97701%; top: 35.6322%; left: 9.53125%; display: block;">DO YOU NEED AN</div>  

style="visibility:hidden;"

 <div style="position: absolute; width: 9999px; visibility: hidden; display: none; max-width: none;"></div>  

type="hidden"

 <input type="hidden" value="form-w1cPBpyG9r-0a26cL3dRYB5fM-V6O_18Ojgef4qOoXo" name="form_build_id">  

Demo Source Code

 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 Hiddenwebelements {  
   public static void main(String[] args) throws InterruptedException {  
     // create objects and variables instantiation     
     WebDriver driver = new FirefoxDriver();  
     // maximize the browser window      
     driver.manage().window().maximize();  
     // launch the firefox browser and open the application url   
     driver.get("http://www.yahoo.com/");  
     //Set timeout     
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //Get all display block invisible webelement and store in List variable name is number_of_displa_block   
     List<WebElement> number_of_displa_block = driver.findElements(By.cssSelector("div[style*='block']"));  
     //Print total size display block webelements   
     System.out.println("Display Block =: " + number_of_displa_block.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_displa_block.size(); i++) {  
       // Print all display block Webelements text   
       if (!(number_of_displa_block.get(i).getText().trim().isEmpty())) {  
         System.out.println("Displa Block Element = " + i + " " + number_of_displa_block.get(i).getAttribute("style").trim() + " " + number_of_displa_block.get(i).getText().trim());  
       } else {  
         System.out.println("Displa Block Element = " + i + " " + number_of_displa_block.get(i).getAttribute("style").trim());  
       }  
     }  
     //Get all display hidden webelemnt and store in List variable name is number_of_visibility_hidden   
     List<WebElement> number_of_visibility_hidden = driver.findElements(By.cssSelector("div[style*='hidden']"));  
     //Print total size visibility hidden webelements    
     System.out.println("\n\nvisibility: hidden = " + number_of_visibility_hidden.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_visibility_hidden.size(); i++) {  
       // Print all hidden Web elements text    
       if (!(number_of_visibility_hidden.get(i).getText().trim().isEmpty())) {  
         System.out.println("visibility: hidden Element = " + i + " " + number_of_visibility_hidden.get(i).getAttribute("style").trim() + " " + number_of_visibility_hidden.get(i).getText().trim());  
       } else {  
         System.out.println("visibility: hidden Element = " + i + " " + number_of_visibility_hidden.get(i).getAttribute("style").trim());  
       }  
     }  
     //Get all display none webelemnt and store in List variable name is number_of_display_none   
     List<WebElement> number_of_display_none = driver.findElements(By.cssSelector("div[style*='none']"));  
     //Print total size display none webelements    
     System.out.println("\n\ndisplay: none = " + number_of_display_none.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_display_none.size(); i++) {  
       // Print all display none Webelements text   
       if (!(number_of_display_none.get(i).getText().trim().isEmpty())) {  
         System.out.println("display: none Element = " + i + " " + number_of_display_none.get(i).getAttribute("style").trim() + " " + number_of_display_none.get(i).getText().trim());  
       } else {  
         System.out.println("display: none Element = " + i + " " + number_of_display_none.get(i).getAttribute("style").trim());  
       }  
     }  
     //Get input tag and store in List variable name is number_of_hidden_input_Elements   
     List<WebElement> number_of_hidden_input_Elements = driver.findElements(By.tagName("input"));  
     //Print total size input hidden webelements   
     System.out.println("\n\nInput Hidden Element =: " + number_of_hidden_input_Elements.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_hidden_input_Elements.size(); i++) {  
       // Print all hidden input webelements value   
       if (number_of_hidden_input_Elements.get(i).getAttribute("type").trim().equalsIgnoreCase("hidden")) {  
         //Check empty text   
         if (!(number_of_hidden_input_Elements.get(i).getAttribute("value").trim().isEmpty())) {  
           //Print hidden Element texts   
           System.out.println("Input Hidden Element = " + i + " " + number_of_hidden_input_Elements.get(i).getAttribute("value").trim());  
         }  
       }  
     }  
     // quit Firefox browser   
     driver.quit();  
   }  
 }  

Clicking an invisible or hidden Element
 List<WebElement> number_of_display_none = driver.findElements(By.cssSelector("div[style*='none']"));  
 JavascriptExecutor executor = JavascriptExecutor)driver;  
 executor.executeScript("arguments[0].click();", number_of_display_none.get(position).getText());  
OR
 WebElement invisibleelement= driver.findElement(ElementLocator);  
 JavascriptExecutor executor = JavascriptExecutor)driver;  
 executor.executeScript("arguments[0].click();", invisibleelement);  

How to get hidden webelements text in Selenium Webdriver using Java


 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 HiddenElementstext {  
   public static void main(String[] args) throws InterruptedException {  
     // create objects and variables instantiation      
     WebDriver driver = new FirefoxDriver();  
     // maximize the browser window       
     driver.manage().window().maximize();  
     // launch the firefox browser and open the application url  
     driver.get("www.yahoo.com");  
     //Set timeout      
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //Get input tag and store in List variable name is number_of_hiddenElements  
     List<WebElement> number_of_hiddenElements = driver.findElements(By.tagName("input"));  
     //Print total number of Input tag   
     System.out.println(number_of_hiddenElements.size());  
     for (int i = 0; i < number_of_hiddenElements.size(); i++) {  
       // Print all hidden elements text  
       if (number_of_hiddenElements.get(i).getAttribute("type").trim().equalsIgnoreCase("hidden")) {  
         //Check empty text  
         if (!(number_of_hiddenElements.get(i).getAttribute("value").trim().isEmpty())) {  
           //Print hidden Element texts  
           System.out.println("Hidden Element text = " + i + " " + number_of_hiddenElements.get(i).getAttribute("value").trim());  
         }  
       }  
     }  
     // quit Firefox browser  
     driver.quit();  
   }  
 }  

How to handle Checkbox and Radio button in Selenium Webdriver using Java.

Checkbox and Radio button operations is very simple to perform like as click operation. Checkbox is always recommended to check if that is already in selected mode or deselected. Because, if it is already selected and when you click on the same element it will get deselected. We will look into different ways to perform select and de-select operations on checkboxes. Radio Button is selected by default or anything.


Page HTML Code

 <html>  
 <head>  
 <title>Checkbox and radio button test page</title>  
 </head>  
 <body>  
 <form name="myform" action="" method="POST">  
 <div align="center"><br>  
 <input type="checkbox" name="option1" value="Bike">Bike  
 <input type="checkbox" name="option2" value="Car">Car   
 <input type="checkbox" name="option3" value="Plane" checked>Plane  
 <input type="checkbox" name="option4" value="Truck">Truck   
 <input type="checkbox" name="option5" value="Milk">Milk  
 <input type="checkbox" name="option6" value="Butter">Butter  
 <input type="checkbox" name="option7" value="Cheese">Cheese  
 <br>  
 <input type="radio" name="group2" value="Water"> Water  
 <input type="radio" name="group2" value="Beer"> Beer  
 <input type="radio" name="group2" value="Wine" checked> Wine  
 </div>  
 </form>  
 </body>  
 </html>  


Demo Source Code

 
 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 CheckboxandRadiobuttonhandler {  
   public static void main(String[] args) throws InterruptedException {  
     // create objects and variables instantiation      
     WebDriver driver = new FirefoxDriver();  
     // maximize the browser window       
     driver.manage().window().maximize();  
     // launch the firefox browser and open the page  
     driver.get("file:///C:/Users/Hiro%20Mia/Desktop/Blog%20content/checkbox.html");  
     //Set timeout      
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //Get the count of all available check boxes   
     List<WebElement> number_of_checkbox = driver.findElements(By.tagName("input"));  

     //Select all checkbox and Radio if selectable  
     for (int i = 0; i < number_of_checkbox.size(); i++) {  
       //Checking Checkbox  
       if (number_of_checkbox.get(i).getAttribute("type").trim().equalsIgnoreCase("checkbox")) {  
         //Print the Check box count with value  
         System.out.println("CheckBox = " + i + " " + number_of_checkbox.get(i).getAttribute("value").trim());  
        
         //Select if aleady not selected  
         if (!(number_of_checkbox.get(i).isSelected())) {  
           number_of_checkbox.get(i).click();  
         } else {  
           //De-select the checkbox  
           number_of_checkbox.get(i).click();  
         }  
       } //Checking Radio button  
       else if (number_of_checkbox.get(i).getAttribute("type").trim().equalsIgnoreCase("radio")) {  
         // //Print the Check box count with value  
         System.out.println("Radio  = " + i + " " + number_of_checkbox.get(i).getAttribute("value").trim());  
         //Select if aleady not selected  
         if (!(number_of_checkbox.get(i).isSelected())) {  
           number_of_checkbox.get(i).click();  
         }  
       }  
       // Pause so that you can see the results.  
       Thread.sleep(3000);  
     }  
 //close firefox browser    
     driver.close();  
   }  
 }  

How to check visibility or appearance or presence of web elements in Selenium Webdriver using Java

Sometime We don't know about the element visible or no that reason we need to check web element is present or visible or enabled or disabled etc. Selenium Webdriver facilitates the user with some methods to check the visibility of the web elements. isSelected(), isEnabled() and isDispalyed() etc methods are used to determine the visibility scope for the web elements.

driver.findElements(By.id("email")).size() ! =0
We need to perform a action based on a specific web element being present or not on the web page. We can return true only when the size of elements is greater than Zero. That mean there exists at least one element.
driver.findElements(By.id("email")).size()>0; or
driver.findElements(By.id("email")).size() ! =0;


isEnabled
Below is the syntax which is used to check if the element is enabled or not
WebElement element = driver.findElement(By.id("email"));
element.isEnabled();


isDisplayed
Below is the syntax which is used to check if the element is displayed or not. It returns false when the element is not present in DOM.
WebElement element = driver.findElement(By.id("email"));
element.isDisplayed();


Demo Source Code
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class PresentElement {

public static void main(String[] args) {
// create objects and variables instantiation     
WebDriver driver = new FirefoxDriver();
// maximize the browser window       
driver.manage().window().maximize();
// launch the firefox browser and open the application url     
driver.get("http://www.facebook.com");
//Set  timeout      
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//To check Element Present
if (driver.findElements(By.id("email")).size() != 0) {
    System.out.println("Element is Present");
} else {
    System.out.println("Element is Absent");
}
//or
if (driver.findElements(By.id("paaswprd")).size() > 0) {
    System.out.println("Element is Present");
} else {
    System.out.println("Element is Absent");
}

//To check Visible
if (driver.findElement(By.id("u_0_v")).isDisplayed()) {
    System.out.println("Element is Visible");
} else {
    System.out.println("Element is InVisible");
}

//To check Enable
if (driver.findElement(By.id("u_0_1")).isEnabled()) {
    System.out.println("Element is Enable");
} else {
    System.out.println("Element is Disabled");
}
// fetch the source of the web page and save it into a string variable
String title = driver.getPageSource();
//To check text present
if (title.contains("Sign Up")) {
    System.out.println("Text is present");
} else {
    System.out.println("Text is absent");
}

//close firefox browser  
driver.close();
    }

}


How to use JavascriptExecutor in Selenium Webdriver using java

JavaScriptExecutor : JavaScriptExecutor is an interface which helps to execute Javascript through selenium driver. It has two 'executescript' & 'executeAsyncScript' methods to run JavaScript in the context of the currently selected frame or window. Javascript plays very important role when we are not able to perform complex operation on the element on the webpage. We can use all HTML DOM methods and properties when using javascript.
In simple words  “Javascript can be executed within the browser with the help of JavaScript Executor.”

Package:
import org.openqa.selenium.JavascriptExecutor;

Methods
Name: executeAsyncScript(java.lang.String script, java.lang.Object... args)
Description: Execute an asynchronous piece of JavaScript in the context of the currently selected frame or window.

Name: executeScript(java.lang.String script, java.lang.Object... args)
Description: Executes JavaScript in the context of the currently selected frame or window.

Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript(Script,Arguments);
        script - The JavaScript to execute
        Arguments - The arguments to the script.(Optional)

The list of Scenario’s below you can handle

Alert Pop window
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('JavascriptExecutor');");

Click a button in Selenium WebDriver using JavaScript
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

Refresh browser window using Javascript
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("history.go(0)");

Get innertext of the entire web page in Selenium Webdriver
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
String sText =  js.executeScript("return document.documentElement.innerText;").toString();

Get Web page title
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
String sText =  js.executeScript("return document.title;").toString();

Handle Scroll on Web page
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
//Vertical scroll - down by 50  pixels
js.executeScript("window.scrollBy(0,50)");

Click on a SubMenu which is only visible on mouse hover on Menu
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
//Hover on Automation Menu on the MenuBar
js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");

Navigate to one page to other page
Code:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.location = 'https://www.google.com/'");


Demo Source Code


 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class JavaScriptExecuterExample {  
 public static void main(String[] args) throws InterruptedException {  
 //Create FireFox object   
 WebDriver driver = new FirefoxDriver();  
 //Launching the browser application  
 driver.get("http://hiromia.blogspot.com/");  
 //10 second waittig time  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
 //Maximize window  
 driver.manage().window().maximize();  
 
//Creating the Javascriptexecutor interface object by Type casting  
 JavascriptExecutor js = (JavascriptExecutor) driver;
  
 //Click on Selenium Webdriver level button  
 js.executeScript("arguments[0].click();", driver.findElement(By.xpath(".//*[@id='Label1']/div/ul/li[3]/a")));  

 //Fetching the Domain Name   
 System.out.println("Domain = " + js.executeScript("return document.domain;").toString());  
 //Fetching the URL     
 System.out.println("URL = " + js.executeScript("return document.URL;").toString());  
 //Fetching the Title  
 System.out.println("Title = " + js.executeScript("return document.title;").toString());  
 //refresh browser window  
 js.executeScript("history.go(0)");  
 Thread.sleep(3000);  

 //Vertical scroll - down by 100 pixels  
 js.executeScript("window.scrollBy(0,1000)");  
 // Navigate to google  
 js.executeScript("window.location = 'https://www.google.com/'");  
 Thread.sleep(5000);  

 //close Firefox  
 driver.quit();  
   }  
 }  







How to handle DOM in Selenium Webdriver using java.


Document Object Model(DOM): The Document Object Model (DOM) is an application programming interface (API). It defines the logical structure of documents and the way Javascript sees its containing pages' data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state.
A DOM element is something like a DIV, HTML, BODY element on a page. You can add classes to all of these using CSS, or interact with them using JS.The DOM strategy works by locating elements that matches the JavaScript expression referring to an element in the DOM of the page.



HTML CODE

There are Three basic ways to locate an element through DOM
getElementById
The value of the ID attribute of the element to be accessed. This value should always be enclosed in a pair of parentheses ('').The most efficient way and preferred way to locate an element on a web page is By ID. ID will be the unique on web page which can be easily identified
Syntax: document.getElementById('id')
id=id of the element
Example:
WebElement email = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.getElementById('email');");
email.sendKeys("abcdef@gmail.com");

getElementsByName
Locates an element using the Class attribute.It collects an array of elements that have the name that you specified. You access the individual elements using an index which starts at 0.
Syntax: document.getElementsByName("name")[index]
name = name of the element as defined by its 'name' attribute
index = an integer that indicates which element within getElementsByName's array will be used.
Example:
WebElement last = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.getElementsByName('name1')[0];");
last.sendKeys("aaaaaa");

Forms
There are four way locate input form. The combination of form locators is given below.
Syntax 1: document.forms[index of the form].elements[index of the element]
Syntax 2: document.forms[index of the form].elements['name of the element']
Syntax 3: document.forms['name of the form'].elements[index of the element]
Syntax 4: document.forms['name of the form'].elements['name of the element']
index of the form = the index number (starting at 0) of the form with respect to the whole page.
index of the element = the index number (starting at 0) of the element with respect to the whole form that contains it.
name of the form =The name of the form as defined by its 'name' attribute and it applies only to elements within a named form.
name of the element: The name of element and defined by 'name' attribute.
Example:
WebElement pass = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.forms['domf2'].elements['password'];");
pass.sendKeys("aaaaaa");

WebElement btn = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.forms[1].elements['butt'];");
btn.click();

Working Demo:-
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.NoSuchElementException;  
 public class DOMhandlerProgram {  
 public static void main(String[] args) throws InterruptedException {  
     try {  
 WebDriver driver = new FirefoxDriver();  
 //Maximize window  
 driver.manage().window().maximize();  
 //Launching the browser page  
 driver.get("file:///C:/Users/Hiro%20Mia/Desktop/Blog%20content/DOM%20locator.html");  
 //Adding wait  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
 
//Creating the Javascriptexecutor interface object by Type casting  
 JavascriptExecutor js = (JavascriptExecutor) driver;  
 //Send email address   
 WebElement email = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.getElementById('email');");  
 email.sendKeys("abcdef@gmail.com");  
 Thread.sleep(3000);  

 //send pass  
 WebElement pass = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.forms['domf2'].elements['password'];");  
 pass.sendKeys("aaaaaa");  
 Thread.sleep(3000);  

 //Click on button  
 WebElement btn = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.forms[1].elements['butt'];");  
 btn.click();  
 WebElement last = (WebElement) ((JavascriptExecutor) driver).executeScript("return document.getElementsByName('name1')[0];");  
 last.sendKeys("aaaaaa");  
 Thread.sleep(3000);  

 //close firefox browser   
 driver.quit();  
     } catch (NoSuchElementException e) {  
     }  
   }  
 }  

How to read data from Properties file in Selenium Webdriver using Java.

'.properties' files have configuration data, database config or project settings etc to maintain project in Java. Each parameter in properties file are stored as a pair of strings, in key and value format and key is case sensitive, where each key is on one line. You can easily read properties from some file using object of type Properties.

In Selenium .properties files are mainly used to store GUI locators / elements, and also Global fields like database configuration details.

The sample properties file that was used for the java program

Here is a example program which demonstrate to read the data from .properties file using Java.

 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.IOException;  
 import java.util.Properties;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.NoSuchElementException;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Readdatafrompro {  
 public static void main(String[] args) {  
 try {  
 // Create FileInputStream Object  
 FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
 // Create Properties object  
 Properties prop = new Properties();  
 //load properties file  
 prop.load(fileInput);  
 //// WebDriver reference but Firefox object  
 WebDriver driver = new FirefoxDriver();  
 //Maximize browser window    
 driver.manage().window().maximize();  

 //Visit to Facebook   
 driver.get(prop.getProperty("URL"));  
 //Read Username from Properties and send to facebook Username text field  
 driver.findElement(By.id("email")).sendKeys(prop.getProperty("Username"));  
 //Read Password from Properties and send to facebook password text field   
 driver.findElement(By.id("pass")).sendKeys(prop.getProperty("Password"));  
 driver.findElement(By.id("loginbutton")).click();  

 if (driver.getPageSource().contains("Please re-enter your password")) {  
   System.out.println("--- Pass ---");  
 } else {  
   System.out.println("!!!! Fail !!!");  
 }  

 //Print Properties Values  
 System.out.println("URL    =: " + prop.getProperty("URL"));  
 System.out.println("User name =: " + prop.getProperty("Username"));  
 System.out.println("Password =: " + prop.getProperty("Password"));  

 // Browser close    
 driver.close();
   
     } catch (FileNotFoundException e) {  
 e.printStackTrace();  
     } catch (IOException e) {  
 e.printStackTrace();  
     } catch (NoSuchElementException e) {  
 e.printStackTrace();  
     }  
   }  
 }  




How to create custom Firefox profile and handle Firefox profile in Selenium Webdriver using Java.

A collection of browser bookmarks, settings, extensions, passwords, history and user preferences call profile, which is stored in a separate location from the browser program files; in short, all of your personal settings.You can have multiple Firefox profiles, each containing a separate set of user information. The Profile Manager allows you to create, remove, rename, and switch profiles. The default Firefox profile is not very automation friendly.  When you want to run automation reliably on a Firefox browser it is advisable to make a separate profile. Automation profile should be light to load and have special proxy and other settings to run good test.

How to create custom Firefox profile

1) At the top of the Firefox window, click on the File menu and then select Exit.

2) Press ‘Windows Key + R’  or click on the Windows Start Menu (bottom left button) and then select Run.

3) In the Run dialog box, type in: ‘firefox.exe -p' and then Click OK.

Note: If the Profile Manager window does not appear, it may be opened in the background. It needs to be closed properly, you may use Ctrl+Alt+Del program to kill it. If it still does not open then you may need to specify the full path of the Firefox program, enclosed in quotes; for example:
On 32-bit Windows: "C:Program FilesMozilla Firefoxfirefox.exe" -p
On 64-bit Windows: "C:Program Files (x86)Mozilla Firefoxfirefox.exe" -p

4) The Choose User Profile window will look like this.

5) Click the ‘Create Profile…’ button on the ‘Firefox – Choose User Profile’ window that comes up.

6) Click ‘Next >’ in the ‘Create Profile Wizard’ window that comes up.

7) Type in a new name ‘profileToolsQA’ in the ‘Enter new profile name’ box and click ‘Finish’.

8) ‘Choose User Profile’ window will display the newly created profile in the list.

9) Click on the ‘Start Firefox’ box. Firefox will start with the new profile.

Note: You will notice that the new Firefox window will not show any of your Bookmarks and Favorite icons.
Note: The last selected profile will then start automatically when you next start Firefox and you will need to start the Profile Manager again to switch profiles.

How to handle new Firefox profile in Selenium Webdriver

Two way We can call custom Firefox profile.

One Way:
ProfilesIni profile = new ProfilesIni();
// Create object for FirefoxProfile
FirefoxProfile myprofile = profile.getProfile("profileToolsQA");
// Initialize Firefox driver     
WebDriver driver = new FirefoxDriver(myprofile)
Example one:
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;

public class HandlecustomProfile1 {
public static void main(String[] args) {

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("profileToolsQA");
  
// Initialize Firefox driver    
WebDriver driver = new FirefoxDriver(myprofile);

//Maximize browser window       
driver.manage().window().maximize();
//Go to URL      
driver.get("http://www.google.com");
//Set  timeout      
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//close firefox browser  
driver.close();
    }

}
Other way:
// Create object for FirefoxProfile
FirefoxProfile myprofile = new FirefoxProfile(new File("C:\\Users\\Hiro Mia\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\giyi7yui.profileToolsQA"));
// Initialize Firefox driver     
WebDriver driver = new FirefoxDriver(myprofile)
Example Two
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;

public class HandlecustomProfile2 {
public static void main(String[] args) {

// Create object for FirefoxProfile
FirefoxProfile myprofile = new FirefoxProfile(new File("C:\\Users\\Hiro Mia\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\giyi7yui.profileToolsQA"));
  
// Initialize Firefox driver    
WebDriver driver = new FirefoxDriver(myprofile);

//Maximize browser window       
driver.manage().window().maximize();
//Go to URL      
driver.get("http://www.yahoo.com");
//Set  timeout      
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//close firefox browser  
driver.close();
    }

}

How to convert color RGB to HEX and HEX to RGB in Selenium Webdriver using Java.

We read font color by getCssValue("color") and it is RGB Format. In Software Requirement Specification (SRS) Color code is Hex format. We need to convert RGB to HEX format or HEX to RGB format for automation. I am going to describe how to convert RGB to HEX color and HEX to RGB color.


 import java.awt.Color;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.NoSuchElementException;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Convertrgbtohex {  
 public static void main(String[] a) {  
 try {  
 // Initialize Firefox driver  
 WebDriver driver = new FirefoxDriver();  
 //Maximize browser window   
 driver.manage().window().maximize();  
 //Go to URL  
 driver.get("http://www.yahoo.com/");  
 //Set selenium webdriver get timeout  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
 String font_name, font_size, font_color;  
 // Get font family name  
 font_name = driver.findElement(By.partialLinkText("My Yahoo")).getCssValue("font-family").trim();  
 // Get font size  
 font_size = driver.findElement(By.partialLinkText("My Yahoo")).getCssValue("font-size").trim();  
 // Get font color RGB code  
 font_color = driver.findElement(By.partialLinkText("My Yahoo")).getCssValue("color").trim();  

 //Print font-family, font-size and font-color  
 System.out.println("font-family : " + font_name);  
 System.out.println("font-size : " + font_size);  
 System.out.println("font-color : " + font_color);  

 // Convert rgb to hex   
 String color1[];  
 color1 = font_color.replace("rgba(", "").split(",");       
 String hex = String.format("#%02x%02x%02x", Integer.parseInt(color1[0].trim()), Integer.parseInt(color1[1].trim()), Integer.parseInt(color1[2].trim()));  
 System.out.println("Convert rgb to hex : " + hex.toUpperCase());  

 //Convert hex to rgb and Print rgb code  
 System.out.println("Convert hex to rgb : rgb (" + Color.decode(hex).getRed() + ", " + Color.decode(hex).getGreen() + ", " + Color.decode(hex).getRed() + ")");  

 // Browser close   
 driver.close();  

 } catch (NoSuchElementException e) {  
 e.printStackTrace();  
     }  
   }  
 }  

How to extend Listener in Selenium WebDriver using java.


Webdriver Listeners: Event listener in WebDriver helps to track events those take place in WebDriver during script execution. It allows do something before or after an action. For example, if you want to wait for an ajax element before every click, or log that action into logger, it is possible to do with the event listener.
AbstractWebDriverEventListener: is a Abstract class
EventFiringWebDriver: This is an class that actually fire Webdriver event

Create a class called AbstractHandle to override events just by Extending AbstractWebDriverEventListener abstract class where AbstractWebDriverEventListener is a abstract which have near about 15 methods that we can override to see after and before tracking of each events that we trigger through our scripts. Creating one object of EventFiringWebDriver just by calling one of its constructor which takes instance of WebDriver.

 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.support.events.AbstractWebDriverEventListener;  
 public class AbstractHandle extends AbstractWebDriverEventListener {  
 //Called after WebElement.clear(), WebElement.sendKeys(...).  
 @Override  
 public void afterChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after WebElement.click()  
 @Override  
 public void afterClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void afterFindBy(By by, WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after navigate().back().  
 @Override  
 public void afterNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after navigate().forward().  
 @Override  
 public void afterNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after get(String url) respectively navigate().to(String url).  
 @Override  
 public void afterNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after RemoteWebDriver.executeScript(String, Object[]).  
 @Override  
 public void afterScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before WebElement.clear(), WebElement.sendKeys(...)  
 @Override  
 public void beforeChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before WebElement.click().    
 @Override  
 public void beforeClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void beforeFindBy(By by, WebElement element, WebDriver driver) {  
 }  
 //Called before navigate().back().  
 @Override  
 public void beforeNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before navigate().forward().  
 @Override  
 public void beforeNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before get(String url) respectively navigate().to(String url).  
 @Override  
 public void beforeNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before RemoteWebDriver.executeScript(String, Object[])  
 @Override  
 public void beforeScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 // Called whenever an exception would be thrown.  
 @Override  
 public void onException(Throwable throwable, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 }  



Create a new Class that implement WebDriverEventListener methods
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.support.events.AbstractWebDriverEventListener;  
 public class AbstractHandle extends AbstractWebDriverEventListenerr {  
 //Called after WebElement.clear(), WebElement.sendKeys(...).  
 @Override  
 public void afterChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("inside method afterChangeValueOf on =: " + element.toString());  
 }  
 //Called after WebElement.click()  
 @Override  
 public void afterClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
  System.out.println("inside method afterClickOn on =: " + element.toString());  
 }  
 //Called after WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void afterFindBy(By by, WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
  System.out.println("Find happened on =: " + by.toString());  
 }  
 //Called after navigate().back().  
 @Override  
 public void afterNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the after navigateback to =: " + driver.getCurrentUrl());  
 }  
 //Called after navigate().forward().  
 @Override  
 public void afterNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the afterNavigateForward to =: " + driver.getCurrentUrl());  
 }  
 //Called after get(String url) respectively navigate().to(String url).  
 @Override  
 public void afterNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the afterNavigateTo to =: " + url);  
 }  
 //Called after RemoteWebDriver.executeScript(String, Object[]).  
 @Override  
 public void afterScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the afterScript to, Script is =: " + script);  
 }  
 //Called before WebElement.clear(), WebElement.sendKeys(...)  
 @Override  
 public void beforeChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the beforeChangeValueOf method =; "+element.toString());  
 }  
 //Called before WebElement.click().    
 @Override  
 public void beforeClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("About to click on the " + element.toString());  
 }  
 //Called before WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void beforeFindBy(By by, WebElement element, WebDriver driver) {  
   System.out.println("before FindBY =: "+by.toString());  
 }  
 //Called before navigate().back().  
 @Override  
 public void beforeNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeNavigateBack =: " + driver.getCurrentUrl());  
 }  
 //Called before navigate().forward().  
 @Override  
 public void beforeNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeNavigateForward =: " + driver.getCurrentUrl());  
 }  
 //Called before get(String url) respectively navigate().to(String url).  
 @Override  
 public void beforeNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeNavigateTo =: " + url);  
 }  
 //Called before RemoteWebDriver.executeScript(String, Object[])  
 @Override  
 public void beforeScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeScript =: " + script);  
 }  
 // Called whenever an exception would be thrown.  
 @Override  
 public void onException(Throwable throwable, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Exception occured at =: " + throwable.getMessage());  
 }  
 }  


Create Event Throwing WebDriver
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import org.openqa.selenium.support.events.EventFiringWebDriver;  

 public class AbstractListernerDemo {  
 public static void main(String[] args) {  
 //Initializing instance of Webdriver  
 WebDriver wDriver = new FirefoxDriver();  

 //Initializing instance of EventFiringWebDriver  
 EventFiringWebDriver driver = new EventFiringWebDriver(wDriver);  
 //Now create object of EventListerHandler to register it with EventFiringWebDriver   
 AbstractHandle handle = new AbstractHandle ();  
 System.out.println("===============================");  
 //register the object of this event listener class with EventFiringWebDriver   
 driver.register(handle); 
 
 driver.get("http://www.facebook.com");  
 driver.findElement(By.id("email")).sendKeys("abcde@gmail.com");  
 driver.findElement(By.id("pass")).sendKeys("aaaaaaaa");  
 driver.findElement(By.id("loginbutton")).click();  
 driver.get("http://www.gmail.com");  
 driver.get("http://www.outlook.com");  
 driver.navigate().back();  
 driver.navigate().forward();  
 driver.quit();  
 driver.unregister(handle);  
 System.out.println("===============================");  
   }  
 }  

Output:
>



How to implement Event Listener Interface in Selenium WebDriver using java.

Webdriver Listeners: Event listener in WebDriver helps to track events those take place in WebDriver during script execution. It allows do something before or after an action. For example, if you want to wait for an ajax element before every click, or log that action into logger, it is possible to do with the event listener.
WebDriverEventListener: is a interface which have near about 15 methods
EventFiringWebDriver: This is an class that actually fire Webdriver event

Create a class called EventListerHandler to override events just by Implementing WebDriverEventListener interface. We can override to see after and before tracking of each events that we trigger through our scripts.
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.support.events.WebDriverEventListener;  
 public class EventListerHandler implements WebDriverEventListener {  
 //Called after WebElement.clear(), WebElement.sendKeys(...).  
 @Override  
 public void afterChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after WebElement.click()  
 @Override  
 public void afterClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void afterFindBy(By by, WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after navigate().back().  
 @Override  
 public void afterNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after navigate().forward().  
 @Override  
 public void afterNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after get(String url) respectively navigate().to(String url).  
 @Override  
 public void afterNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called after RemoteWebDriver.executeScript(String, Object[]).  
 @Override  
 public void afterScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before WebElement.clear(), WebElement.sendKeys(...)  
 @Override  
 public void beforeChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before WebElement.click().    
 @Override  
 public void beforeClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void beforeFindBy(By by, WebElement element, WebDriver driver) {  
 }  
 //Called before navigate().back().  
 @Override  
 public void beforeNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before navigate().forward().  
 @Override  
 public void beforeNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before get(String url) respectively navigate().to(String url).  
 @Override  
 public void beforeNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 //Called before RemoteWebDriver.executeScript(String, Object[])  
 @Override  
 public void beforeScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 // Called whenever an exception would be thrown.  
 @Override  
 public void onException(Throwable throwable, WebDriver driver) {  
 // TODO Auto-generated method stub  
 }  
 }  



Create a new Class that implement WebDriverEventListener methods
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.support.events.WebDriverEventListener;  
 public class EventListerHandler implements WebDriverEventListener {  
 //Called after WebElement.clear(), WebElement.sendKeys(...).  
 @Override  
 public void afterChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("inside method afterChangeValueOf on =: " + element.toString());  
 }  
 //Called after WebElement.click()  
 @Override  
 public void afterClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
  System.out.println("inside method afterClickOn on =: " + element.toString());  
 }  
 //Called after WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void afterFindBy(By by, WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
  System.out.println("Find happened on =: " + by.toString());  
 }  
 //Called after navigate().back().  
 @Override  
 public void afterNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the after navigateback to =: " + driver.getCurrentUrl());  
 }  
 //Called after navigate().forward().  
 @Override  
 public void afterNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the afterNavigateForward to =: " + driver.getCurrentUrl());  
 }  
 //Called after get(String url) respectively navigate().to(String url).  
 @Override  
 public void afterNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the afterNavigateTo to =: " + url);  
 }  
 //Called after RemoteWebDriver.executeScript(String, Object[]).  
 @Override  
 public void afterScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the afterScript to, Script is =: " + script);  
 }  
 //Called before WebElement.clear(), WebElement.sendKeys(...)  
 @Override  
 public void beforeChangeValueOf(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Inside the beforeChangeValueOf method =; "+element.toString());  
 }  
 //Called before WebElement.click().    
 @Override  
 public void beforeClickOn(WebElement element, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("About to click on the " + element.toString());  
 }  
 //Called before WebDriver.findElement(...), or WebDriver.findElements(...), or WebElement.findElement(...), or WebElement.findElements(...).  
 @Override  
 public void beforeFindBy(By by, WebElement element, WebDriver driver) {  
   System.out.println("before FindBY =: "+by.toString());  
 }  
 //Called before navigate().back().  
 @Override  
 public void beforeNavigateBack(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeNavigateBack =: " + driver.getCurrentUrl());  
 }  
 //Called before navigate().forward().  
 @Override  
 public void beforeNavigateForward(WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeNavigateForward =: " + driver.getCurrentUrl());  
 }  
 //Called before get(String url) respectively navigate().to(String url).  
 @Override  
 public void beforeNavigateTo(String url, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeNavigateTo =: " + url);  
 }  
 //Called before RemoteWebDriver.executeScript(String, Object[])  
 @Override  
 public void beforeScript(String script, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Just before beforeScript =: " + script);  
 }  
 // Called whenever an exception would be thrown.  
 @Override  
 public void onException(Throwable throwable, WebDriver driver) {  
 // TODO Auto-generated method stub  
 System.out.println("Exception occured at =: " + throwable.getMessage());  
 }  
 }  


Create Event Throwing WebDriver
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import org.openqa.selenium.support.events.EventFiringWebDriver;  

 public class EventListerDemo {  
 public static void main(String[] args) {  
 //Initializing instance of Webdriver  
 WebDriver wDriver = new FirefoxDriver();  

 //Initializing instance of EventFiringWebDriver  
 EventFiringWebDriver driver = new EventFiringWebDriver(wDriver);  
 //Now create object of EventListerHandler to register it with EventFiringWebDriver   
 EventListerHandler handle = new EventListerHandler();  

 System.out.println("===============================");  
 //Registering it with EventFiringWebDriver   
 driver.register(handle);  
 driver.get("http://www.facebook.com");  
 driver.findElement(By.id("email")).sendKeys("abcde@gmail.com");  
 driver.findElement(By.id("pass")).sendKeys("aaaaaaaa");  
 driver.findElement(By.id("loginbutton")).click();  
 driver.get("http://www.gmail.com");  
 driver.get("http://www.outlook.com");  
 driver.navigate().back();  
 driver.navigate().forward();  
 driver.quit();  
 driver.unregister(handle);  
 System.out.println("===============================");  
   }  
 }  

Output:
>