Showing posts with label Selenium Webdriver. Show all posts
Showing posts with label Selenium Webdriver. Show all posts

How to encode or encrypt password and other personal information in Selenium Webdriver using Java

Daily we sign in many popular websites like Facebook, Gmail, LinkedIn etc. with login credential. We need to send password as plain text to sign in those popular websites if want to write automation login script in selenium webdriver. One of the most common practice to send encrypted passwords and other personal information instead of plain text for the automation login script.

Base64: Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.
 byte[] encodedBytes = Base64.encodeBase64("TextforEncoding".getBytes());  
 System.out.println("encodedBytes " + new String(encodedBytes));  
 byte[] decodedBytes = Base64.decodeBase64(encodedBytes);  
 System.out.println("decodedBytes " + new String(decodedBytes));  
Prerequisite
1. Create a 'data.properties' file your project home directory
2. Download Base64 jar file and add jar file in project as external jar.

Demo Source code:
 import org.apache.commons.codec.binary.Base64;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.Properties;  
 import java.util.concurrent.TimeUnit;    
   
 public class Encryptionpassword {  
   private static By email = By.id("email");  
   private static By password = By.id("pass");  
   private static By loginbutton = By.id("u_0_m");  
   
   public static void main(String[] arg) throws IOException {  
   
     // Create FileInputStream Object  
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object  
     Properties prop = new Properties();  
     //load properties file  
     prop.load(fileInput);  
   
     // create Firebox object  
     WebDriver driver = new FirefoxDriver();  
     //Go to URL  
     driver.get("http://www.facebook.com");  
     //Maximize browser window  
     driver.manage().window().maximize();  
     //Set timeout  
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
   
     driver.findElement(email).clear();  
     driver.findElement(email).sendKeys(prop.getProperty("username"));  
   
     driver.findElement(password).clear();  
     driver.findElement(password).sendKeys(new String(Base64.encodeBase64(prop.getProperty("password").getBytes())));  
   
     driver.findElement(loginbutton).click();  
   
     //Print Encrypted Password  
     System.out.println("Encrypted Password =: " + new String(Base64.encodeBase64(prop.getProperty("password").getBytes())));  
     //Print Decrypted Password  
     System.out.println("Decrypted Password =: " + new String(Base64.decodeBase64(Base64.encodeBase64(prop.getProperty("password").getBytes()))));  
   
     //close firefox browser  
     driver.close();  
   }  
 }  
   

Output:

How to operate new single window or multiple windows in selenium webdriver using java

Some Web application allows to login to their system using Gmail, Facebook, Twitter etc account. When click on Gmail, Facebook, Twitter, its icon button, new window open with a login page. Selenium webdriver provide opportunity to handle new opened window and back to original window after completing an operation on new window. In this tutorial I will show how to operate new window.


Switch between new opened windows and original window as below:
 
// Store the current window on String variable  
 String parentwindow = driver.getWindowHandle();  

 // Do the click operation that opens new window  
 // Switch to window that's your newly opened window  

 for(String winHandle : driver.getWindowHandles()){  
   driver.switchTo().window(winHandle);  
 }  

 // code to do something on new window  

 // Close the new window, if that window no more required  
 driver.close();  

 // Switch back to original browser (parent window)  
 driver.switchTo().window(parentwindow);  

 // Continue with original browser (parent window)  

Java demo source code:
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Operatenewwindow {  
   public static void main(String[] arg) {  
     WebDriver driver = new FirefoxDriver();  
     driver.manage().window().maximize();  
     driver.get("http://localhost:8080/idea/a/community/login");  

     // Store the current window on String variable  
     String parentwindow = driver.getWindowHandle();  
 // Do the click operation that opens new window  
     driver.findElement(By.className("icon-facebook")).click(); 
 
 // Switch to window that's your newly opened window  
     for (String winHandle : driver.getWindowHandles()) {  
       driver.switchTo().window(winHandle);  
     }  

 // code to do something on new window  
     driver.findElement(By.id("email")).sendKeys("hiro@gmail.com");  
     driver.findElement(By.id("pass")).sendKeys("123456789");  
     driver.findElement(By.id("loginbutton")).click();  

 // Close the new window, if that window no more required  
     driver.close();  

 // Switch back to original browser (parent window)  
     driver.switchTo().window(parentwindow); 

 
 // Continue with original browser (parent window)  
     driver.close();  
   }  
 }  

How to handle WebDriverException: Element is not clickable at point using java

Some case the element position is not fixed and we want to do some action like click button on that particular element then result an error as 'Exception in thread "main" org.openqa.selenium.WebDriverException: Element is not clickable at point (xx, yy). Other element would receive the click:'. This happens when the element is loaded into the DOM, but the position is not fixed on the UI. There can be some other divs or images or ads that are not loaded completely.

The different workable solutions provided below.
 1. Maximize browser window
 driver.manage().window().maximize();

 2. The page is getting refreshed before clicking on element.

 3. Scroll to element using Keys
driver.findElement(By.id("ID of the element")).sendKeys(Keys.PAGE_DOWN); 
 or
driver.findElement(By.id("ID of the element")).sendKeys(Keys.PAGE_UP);

4. Click on element using  Actions Class
WebElement element = driver.findElement(By.id("login-button"));
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();


5. Page scroll up or down using JavaScriptExecutor
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)"); // if the element is on top.
jse.executeScript("scroll(0, 250)"); // if the element is on bottom. 


6. Page move particular X or Y position using JavaScriptExecutor if element is not visible
 WebElement element = driver.findElement(By.id("login-button"));
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,"element.getLocation().x+")");
element.click();

or
WebElement element = driver.findElement(By.id("login-button"));
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,"element.getLocation().y+")");
element.click();

or
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView()", driver.findElement(By.id("login-button"));


7.Element is not present at the time of execution. Use WebDriverWait to until the element is present.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("ID of the element")));

How can handle unexpected alert exception in Selenium Webdriver using java

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.NoAlertPresentException;  
 import org.openqa.selenium.UnhandledAlertException;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Unexpectedalert {  
   public static void main(String[] args) {  
     WebDriver driver;  
     // creat firefox driver object    
     driver = new FirefoxDriver();  
     //Maximize browser window    
     driver.manage().window().maximize();  
     //Go to URL    
     driver.get("http://localhost:80/ideascalechallenge");  
     //Set timeout   
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 

 
 // handle Alert Exception  
     try {  
 // trigger unexpected alter event  
       driver.get("http://localhost:80/ideascalechallenge/a/idea?templateId=0");  
     } catch (UnhandledAlertException f) {  
       try {  
         Alert alert = driver.switchTo().alert();  
         String alertText = alert.getText();  
         System.out.println("Alert data: " + alertText);  
         alert.accept();  
         //or  depend event
         // alert.dismiss();  
       } catch (NoAlertPresentException e) {  
         e.printStackTrace();  
       }  
     }
  
   }  
 }  

How to send Selenium Webdriver testing summary report in a Simple or an HTML or Attachment E-mail using java.

We use Selenium Webdiver automation tool for Web functional and regression testing. We run many test cases using that tool. Sometime We need to send summary testing report which reports include how many test cases are successfully passed or failed. In this tutorial I will show how to send Selenium Webdriver testing summary report in a Simple or an HTML or Attachment E-mail.


Download mail.jar and add desired project
Send a Simple E-mail
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 import javax.mail.*;  
 import javax.mail.internet.*;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Sendsimpleemail {  
   static Properties prop = null;  
   static String urls = "";  
   public static void main(String[] args) throws IOException {  
     List<WebElement> urllist = new ArrayList();  
     // Initialize driver     
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window      
     driver.manage().window().maximize();  
     //Go to URL     
     driver.get("https://www.yahoo.com/");  
     //Set timeout     
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     urllist = driver.findElements(By.tagName("a"));  
     try {  
       for (WebElement url : urllist) {  
         if ((url.getAttribute("href").trim().length() > 4) && (url.getAttribute("href").trim().contains("yahoo.com")) && !(url.getAttribute("href").trim().contains("javascript:void(0)"))) {  
           urls = urls + url.getAttribute("href").trim() + "\n";  
         }  
       }  
     } catch (NullPointerException e) {  
 //      e.printStackTrace();  
     }  
     System.out.println(urls);  
     //close firefox browser   
     driver.close();  
     // Recipient's email ID needs to be mentioned.  
     String to = "hiromia006@gmail.com";  
     // Assuming you are sending email from localhost  
     String host = "localhost";  
     // Create FileInputStream Object   
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object      
     prop = new Properties();  
     //load properties file   
     prop.load(fileInput);  
     // Get system properties  
     Properties properties = System.getProperties();  
     // Setup mail server  
     properties.setProperty("mail.smtp.host", host);  
     properties.put("mail.smtp.starttls.enable", "true");  
     properties.put("mail.smtp.host", "smtp.gmail.com");  
     properties.put("mail.smtp.user", prop.getProperty("From_email")); // User name  
     properties.put("mail.smtp.password", prop.getProperty("From_email_password")); // password  
     properties.put("mail.smtp.port", "587");  
     properties.put("mail.smtp.auth", "true");  
     Authenticator authenticator = new Authenticator() {  
       public PasswordAuthentication getPasswordAuthentication() {  
         return new PasswordAuthentication(prop.getProperty("From_email"), prop.getProperty("From_email_password"));//userid and password for "from" email address   
       }  
     };  
     // Get the default Session object.  
     Session session = Session.getDefaultInstance(properties, authenticator);  
     try {  
       // Create a default MimeMessage object.  
       MimeMessage message = new MimeMessage(session);  
       // Set From: header field of the header.  
       message.setFrom(new InternetAddress(prop.getProperty("From_email")));  
       // Set To: header field of the header.  
       message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
       // Set Subject: header field  
       message.setSubject("Yahoo Home page internet links");  
       // Now set the actual message  
       message.setText(urls);  
       // Send message  
       Transport.send(message);  
       System.out.println("Sent message successfully....");  
     } catch (MessagingException mex) {  
       mex.printStackTrace();  
     }  
   }  
 }  

Send an HTML E-mail
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 import javax.mail.*;  
 import javax.mail.internet.*;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Sendanhtmlemail {  
   static Properties prop = null;  
   static String urltexts = "";  
   public static void main(String[] args) throws IOException {  
     List<WebElement> urllist = new ArrayList();  
     // Initialize driver  
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window  
     driver.manage().window().maximize();  
     //Go to URL  
     driver.get("https://www.google.com/");  
     //Set timeout  
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     urllist = driver.findElements(By.tagName("a"));  
     try {  
       for (WebElement url : urllist) {  
         if ((url.getText().trim().length() > 1) && !(url.getText().trim().contains("null"))) {  
           urltexts = urltexts + "<h1>"+url.getText().trim() + "<h1>\n";  
         }  
       }  
     } catch (NullPointerException e) {  
       //   e.printStackTrace();  
     }  
     System.out.println(urltexts);  
     //close firefox browser  
     driver.close();  
     // Recipient's email ID needs to be mentioned.  
     String to = "hiromia006@gmail.com";  
     // Assuming you are sending email from localhost  
     String host = "localhost";  
     // Create FileInputStream Object  
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object  
     prop = new Properties();  
     //load properties file  
     prop.load(fileInput);  
     // Get system properties  
     Properties properties = System.getProperties();  
     // Setup mail server  
     properties.setProperty("mail.smtp.host", host);  
     properties.put("mail.smtp.starttls.enable", "true");  
     properties.put("mail.smtp.host", "smtp.gmail.com");  
     properties.put("mail.smtp.user", prop.getProperty("From_email")); // User name  
     properties.put("mail.smtp.password", prop.getProperty("From_email_password")); // password  
     properties.put("mail.smtp.port", "587");  
     properties.put("mail.smtp.auth", "true");  
     Authenticator authenticator = new Authenticator() {  
       public PasswordAuthentication getPasswordAuthentication() {  
         return new PasswordAuthentication(prop.getProperty("From_email"), prop.getProperty("From_email_password"));//userid and password for "from" email address  
       }  
     };  
     // Get the default Session object.  
     Session session = Session.getDefaultInstance(properties, authenticator);  
     try {  
       // Create a default MimeMessage object.  
       MimeMessage message = new MimeMessage(session);  
       // Set From: header field of the header.  
       message.setFrom(new InternetAddress(prop.getProperty("From_email")));  
       // Set To: header field of the header.  
       message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
       // Set Subject: header field  
       message.setSubject("Google Home page internet links text");  
       // Send the actual HTML message, as big as you like  
       message.setContent(urltexts, "text/html" );  
       // Send message  
       Transport.send(message);  
       System.out.println("Sent message successfully....");  
     } catch (MessagingException mex) {  
       mex.printStackTrace();  
     }  
   }  
 }  

Send Attachment in E-mail
 import java.io.*;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 import javax.mail.*;  
 import javax.mail.internet.*;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import javax.activation.*;  
 public class SendAttachmentemail {  
   static Properties prop = null;  
   static String urls = "";  
   static File file;  
   public static void main(String[] args) throws IOException {  
     List<WebElement> urllist = new ArrayList();  
     // Initialize driver  
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window  
     driver.manage().window().maximize();  
     //Go to URL  
     driver.get("https://www.yahoo.com/");  
     //Set timeout  
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     urllist = driver.findElements(By.tagName("a"));  
     try {  
       for (WebElement url : urllist) {  
         if ((url.getAttribute("href").trim().length() > 4) && (url.getAttribute("href").trim().contains("yahoo.com")) && !(url.getAttribute("href").trim().contains("javascript:void(0)"))) {  
           urls = urls + url.getAttribute("href").trim() + "\n";  
         }  
       }  
     } catch (NullPointerException e) {  
       //   e.printStackTrace();  
     }  
     try {  
       file = new File("Internetlinks.txt");  
       // if file doesnt exists, then create it  
       if (!file.exists()) {  
         file.createNewFile();  
       }  
       // Write text on txt file.  
       FileWriter fw = new FileWriter(file, true);  
       BufferedWriter bw = new BufferedWriter(fw);  
       bw.write(urls);  
       bw.close();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
     System.out.println(urls);  
     //close firefox browser  
     driver.close();  
     // Recipient's email ID needs to be mentioned.  
     String to = "hiromia006@gmail.com";  
     // Assuming you are sending email from localhost  
     String host = "localhost";  
     // Create FileInputStream Object  
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object  
     prop = new Properties();  
     //load properties file  
     prop.load(fileInput);  
     // Get system properties  
     Properties properties = System.getProperties();  
     // Setup mail server  
     properties.setProperty("mail.smtp.host", host);  
     properties.put("mail.smtp.starttls.enable", "true");  
     properties.put("mail.smtp.host", "smtp.gmail.com");  
     properties.put("mail.smtp.user", prop.getProperty("From_email")); // User name  
     properties.put("mail.smtp.password", prop.getProperty("From_email_password")); // password  
     properties.put("mail.smtp.port", "587");  
     properties.put("mail.smtp.auth", "true");  
     Authenticator authenticator = new Authenticator() {  
       public PasswordAuthentication getPasswordAuthentication() {  
         return new PasswordAuthentication(prop.getProperty("From_email"), prop.getProperty("From_email_password"));//userid and password for "from" email address  
       }  
     };  
     // Get the default Session object.  
     Session session = Session.getDefaultInstance(properties, authenticator);  
     try {  
       // Create a default MimeMessage object.  
       MimeMessage message = new MimeMessage(session);  
       // Set From: header field of the header.  
       message.setFrom(new InternetAddress(prop.getProperty("From_email")));  
       // Set To: header field of the header.  
       message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
       // Set Subject: header field  
       message.setSubject("Yahoo Home page internet links attached text field");  
       // Create the message part  
       BodyPart messageBodyPart = new MimeBodyPart();  
       // Fill the message  
       messageBodyPart.setText("have sent Yahoo home page url list by attached file");  
       // Create a multipar message  
       Multipart multipart = new MimeMultipart();  
       // Set text message part  
       multipart.addBodyPart(messageBodyPart);  
       // Part two is attachment  
       messageBodyPart = new MimeBodyPart();  
       DataSource source = new FileDataSource("Internetlinks.txt");  
       messageBodyPart.setDataHandler(new DataHandler(source));  
       messageBodyPart.setFileName("Internetlinks.txt");  
       multipart.addBodyPart(messageBodyPart);  
       // Send the complete message parts  
       message.setContent(multipart );  
       // Send message  
       Transport.send(message);  
       System.out.println("Sent message successfully....");  
     } catch (MessagingException mex) {  
       mex.printStackTrace();  
     }  
   }  
 }  

How can open and close browser tabs in selenium Webdriver on Mac using java.

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.Keys;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Openandclosetabhandler {  
   public static void main(String[] a) throws InterruptedException {  
     // Initialize driver   
     WebDriver driver = new FirefoxDriver();  
     //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);  
     // Open new tab   
     driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");  
     //Go to URL   
     driver.get("http://www.yahoo.com/");  
     //Set new tab timeout   
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // Do some operation       
     driver.findElement(By.partialLinkText("Sign in")).click();  
     Thread.sleep(2000);  
     // Switch first tab   
     driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "w");  
     driver.switchTo().defaultContent();  
     Thread.sleep(2000);  
     // Operation   
     driver.findElement(By.partialLinkText("Gmail")).click();  
     Thread.sleep(2000);  
     // Browser close    
     driver.close();  
   }  
 }  

How to get HTML tag Attribute values in Selenium Webdriver using Java.

Sometime We need to get the attribute values to perform some operation. In this tutorial I show how to get tag attribute values using Selenium Webdriver.

In the below HTML code, You see input tag which has multiple attribute 'type', 'class', 'name', 'id', 'autocomplete', 'autocomplete', 'value' and 'title' and hash values for each attribute. To get the attribute value, We need to use below selenium webdriver syntax.

Syntax: webelement_select+tag.getAttribute(attributeName).

We try to get the attribute value that doesn't exists for the tag, it will return null value.
 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>Get Attribute values</title>  
 </head>  
 <body>  
 <h1>Get Attribute values</h1>  
 <form name="domf1" method="post">  
 <div>  
  <label for="Email" class="class-name1 class-name2"> Enter your email</label>  
  <input type="email" class="class-name3 class-name1 class-name2 class-name4" name="btnK" id="gbqfba" autocomplete="off" value="" title="Search">  
 </div>  
 </form>   
  </body>  
 </html>   
Implementation Selenium Webdriver Source code for Upper HTML 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;  
 public class Getattributevalueshandler {  
   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("file:///C:/Users/Hiro%20Mia/Desktop/Blog%20content/Attribute.html");  
     //Set timeout     
 //    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // identify input tag by proper selector  
     WebElement inputtag = driver.findElement(By.id("gbqfba"));  
     // Print all attribute value under unput tag  
     System.out.println("The Atribute of type value     =: " + inputtag.getAttribute("type"));  
     System.out.println("The Atribute of class value    =: " + inputtag.getAttribute("class"));  
     System.out.println("The Atribute of name value     =: " + inputtag.getAttribute("name"));  
     System.out.println("The Atribute of autocomplete value =: " + inputtag.getAttribute("autocomplete"));  
     System.out.println("The Atribute of title value    =: " + inputtag.getAttribute("title"));  
     System.out.println("The Atribute of href value     =: " + inputtag.getAttribute("href"));  
     // close browser  
     driver.close();  
   }  
 }  
After running the above code the output should look something like below:

How to handle combined multiple classes in Selenium Webdriver using java.

Selenium Webdriver have different types of locators to identify a web element uniquely within the webpage and ClassName one of them. Single className, We can easy way identify web element, but multiple Class Name need to follow technique. In this tutorial I discuss how to operate multiple class names The list of locators is given below.
ID, ClassName, Name, TagName, LinkText, PartialLinkText, Xpath, CSS Selector, DOM
There are there important special characters:
1. '^' symbol, represents the starting text in a string.
2. '$' symbol represents the ending text in a string.
3. '*' symbol represents contains text in a string.
  <label for="Email" class="class-name1 class-name2"> Enter your email</label>  
  <input type="email" class="class-name3 class-name1 class-name2 class-name4">  
Css Selector and XPath help to identify multiple Classes. For this case, Css Selector is always fast, concise, native than XPath.
Css Selector
 //Match exact class  
 WebElement ele1 = driver.findElement(By.cssSelector("label.class-name1"));  
 System.out.println(ele1.getText().trim());  
 WebElement ele2 = driver.findElement(By.cssSelector("input.class-name1.class-name3"));  
 ele2.sendKeys("ele2@gmail.com");  
 WebElement ele3 = driver.findElement(By.cssSelector("input.class-name1.class-name2"));  
 ele3.clear();  
 ele3.sendKeys("ele3@gmail.com");  
 WebElement ele4 = driver.findElement(By.cssSelector("input[class='class-name3 class-name1 class-name2 class-name4']"));  
 ele4.clear();  
 ele4.sendKeys("ele4@gmail.com");  
 //match start class pattern calss  
 WebElement ele5 = driver.findElement(By.cssSelector("input[class^='class-name3']"));  
 ele5.clear();  
 ele5.sendKeys("ele5@gmail.com");  
 //match end class pattern calss  
 WebElement ele6 = driver.findElement(By.cssSelector("input[class$='class-name4']"));  
 ele6.clear();  
 ele6.sendKeys("ele6@gmail.com");  
 Thread.sleep(5000);  
 //match contain class pattern calss  
 WebElement ele7 = driver.findElement(By.cssSelector("input[class*='class-name3']"));  
 ele7.clear();  
 ele7.sendKeys("ele7@gmail.com");  
XPath
 //Match exact class  
 System.out.println(driver.findElement(By.xpath("//label[@class='class-name1 class-name2']")).getText().trim());  
 //match class order matters contains value  
 WebElement e2e1 = driver.findElement(By.xpath("//input[contains(@class, 'class-name3')]"));  
 e2e1.clear();  
 e2e1.sendKeys("e2e1@gmail.com");  
 //match as long as elements have one more classes with contains  
 WebElement e2e2 = driver.findElement(By.xpath("//input[contains(@class, 'class-name1') and contains(@class, 'class-name4')]"));  
 e2e2.clear();  
 e2e2.sendKeys("e2e2@gmail.com");  
Demo HTML page
 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>Multiple Class</title>  
 </head>  
 <body>  
 <h1>Multiple Class</h1>  
 <form name="domf1" method="post">  
 <div>  
  <label for="Email" class="class-name1 class-name2"> Enter your email</label>  
  <input type="email" class="class-name3 class-name1 class-name2 class-name4">  
 </div>  
 </form>   
  </body>  
 </html>   
Implementation Selenium Webdriver Source code for Upper HTML 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;  
 public class Multipleclasshandler {  
   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("file:///C:/Users/Hiro%20Mia/Desktop/Blog%20content/handle%20multiple%20class.html");  
     //Set timeout     
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //Match exact class  
     WebElement ele1 = driver.findElement(By.cssSelector("label.class-name1"));  
     System.out.println(ele1.getText().trim());  
     WebElement ele2 = driver.findElement(By.cssSelector("input.class-name1.class-name3"));  
     ele2.sendKeys("ele2@gmail.com");  
     Thread.sleep(2000);  
     WebElement ele3 = driver.findElement(By.cssSelector("input.class-name1.class-name2"));  
     ele3.clear();  
     ele3.sendKeys("ele3@gmail.com");  
     Thread.sleep(2000);  
     WebElement ele4 = driver.findElement(By.cssSelector("input[class='class-name3 class-name1 class-name2 class-name4']"));  
     ele4.clear();  
     ele4.sendKeys("ele4@gmail.com");  
     Thread.sleep(2000);  
     //match start class pattern calss  
     WebElement ele5 = driver.findElement(By.cssSelector("input[class^='class-name3']"));  
     ele5.clear();  
     ele5.sendKeys("ele5@gmail.com");  
     Thread.sleep(2000);  
     //match end class pattern calss  
     WebElement ele6 = driver.findElement(By.cssSelector("input[class$='class-name4']"));  
     ele6.clear();  
     ele6.sendKeys("ele6@gmail.com");  
     Thread.sleep(5000);  
     //match contain class pattern calss  
     WebElement ele7 = driver.findElement(By.cssSelector("input[class*='class-name3']"));  
     ele7.clear();  
     ele7.sendKeys("ele7@gmail.com");  
     Thread.sleep(2000);  
     //Match exact class  
     System.out.println(driver.findElement(By.xpath("//label[@class='class-name1 class-name2']")).getText().trim());  
     //match class order matters contains value  
     WebElement e2e1 = driver.findElement(By.xpath("//input[contains(@class, 'class-name3')]"));  
     e2e1.clear();  
     e2e1.sendKeys("e2e1@gmail.com");  
     Thread.sleep(2000);  
     //match as long as elements have one more classes with contains  
     WebElement e2e2 = driver.findElement(By.xpath("//input[contains(@class, 'class-name1') and contains(@class, 'class-name4')]"));  
     e2e2.clear();  
     e2e2.sendKeys("e2e2@gmail.com");  
     Thread.sleep(2000);  
     // quit Firefox browser    
     driver.quit();  
   }  
 }  

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