Automation Using Selenium Webdriver

Sunday, 23 October 2016

Print the name of friends with the status like one is online, busy, idle or offline in gmail chat.

Print the name of friends with the status like one is online, busy, idle or offline in gmail chat.

Note- Please give the gmail id and password while runtime. (after pressing ctrl+f11).

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

public class GmailOnlinePeople {

   public static void main(String[] args) {
    WebDriver driver;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the gmail id: ");
    String emailId = in.next();
    System.out.println("Enter the pass: ");
    String pass = in.next();

    driver = new FirefoxDriver(); //open firefox browser

    //login to gmail
    driver.get("http://www.gmail.com");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(40,TimeUnit.SECONDS);
    driver.findElement(By.name("Email")).sendKeys(emailId);
    driver.findElement(By.name("Passwd")).sendKeys(pass);
    driver.findElement(By.name("signIn")).click();
    String name="";
    //friends with available status
       
                  try
                  {
        List<WebElement> available = driver.findElements(By.xpath("//tr[td[img[contains(@alt,'Available')]]]//td[2]/span[1]"));
        System.out.println("number of friends with available status in the gmail chat: "+available.size());
        if(available.size()!=0){
            System.out.println("Name of the friends with Available status: ");
        }
        for (int i=0; i <available.size(); i++)
        {
            name = available.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    } catch (NoSuchElementException e) {
        System.out.println("No one is there with available status.");
    }
 
  //friends with busy status in the gmail chat

             try
 {
        List<WebElement> busy = driver.findElements(By.xpath("//tr[td[img[@alt='Busy']]]//td[2]/span[1]"));
        System.out.println("number of friends with busy status in the gmail chat: "+busy.size());
        if(busy.size()!=0){
            System.out.println("Name of the friends with busy status: ");
        }
        for (int i=0; i <busy.size(); i++)
        {
            name = busy.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    } catch (NoSuchElementException e) {
        System.out.println("No one is with busy status.");
    }
 
  //friends with idle status
   
                    try
             {
        List<WebElement> idle =                 driver.findElements(By.xpath("//tr[td[img[@alt='Idle']]]//td[2]/span[1]"));
        System.out.println("number of friends with idle status in the gmail chat: "+idle.size());
        if(idle.size()!=0){
            System.out.println("Name of the friends with idle status: ");
        }
        for (int i=0; i <idle.size(); i++)
        {
            name = idle.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    }
            catch (NoSuchElementException e)
{
        System.out.println("No one is with idle status.");
    }
 
  //friends with offline status
                     try {
        List<WebElement> offline =                                               driver.findElements(By.xpath("//tr[td[img[@alt='Offline']]]//td[2]/span[1]"));
        System.out.println("number of friends offline in the gmail chat: "+offline.size());
        if(offline.size()!=0)
                {
               System.out.println("Name of the friends offline: ");
        }
                                     for (int i=0; i <offline.size(); i++)
                      {
            name = offline.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    }          
                      catch (NoSuchElementException e)
              {
                     System.out.println("No one is offline.");
             }
                           driver.close();
                 }
}

Datepicker using Selenium WebDriver

Calendars look pretty and of course they are fancy too.So now a days most of the websites are using advancedjQuery Datepickers instead of displaying individual dropdowns for month,day,year. :P

If we look at the Datepicker, it is just a like a table with set of rows and columns.To select a date ,we just have to navigate to the cell where our desired date is present.

Step 1:  Here I am taking Sample Website "http://www.cleartrip.com/"
step 2:  Here we can able to select date whatever we want( This is pure dynamic)
step 3:  Here I am Implementing all my logic in 'genericDatePicker()' Method. This method i am   passing date(date format should be dd/mm/yyyy).
step 4: Here First I am Clicking Calendar field and then i am getting Month/Year.
Step 5: I have written Enum method(I am assigning Number to every Month)
Step 6: After that I am calculating total months.
Step 7: Finally I am Clicking the Date From DatePicker..

Here is a sample code on how to pick a 26/10/2016..


package com.utility;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver; 
public class RedBus {
  WebDriver driver;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.get("http://www.cleartrip.com/");
driver.manage().window().maximize();
}

@Test
public  void datePicker(){
genericDatePicker("26/09/2016");  //date format should be dd/mm/yy
}

public  void genericDatePicker(String inputDate){
/* CLicking the Date Feild*/
WebElement ele =driver.findElement(By.id("DepartDate"));  
ele.click();
/*Here we are getting Month and Year */
String month = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[1]")).getText();
String year = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[2]")).getText();
System.out.println("Application month : "+month + " Year :"+year);
int monthNum = getMonthNum(month);
System.out.println("Enum Num : "+monthNum);
String[] parts = inputDate.split("/");   // Here I am Spliting Our Input String Value
//Here I am Implementing the Logic
int noOfHits = ((Integer.parseInt(parts[2])-Integer.parseInt(year))*12)+(Integer.parseInt(parts[1])-monthNum);
System.out.println("No OF Hits "+noOfHits);
for(int i=0; i< noOfHits;i++){
driver.findElement(By.className("nextMonth ")).click();
}
/* selecting the month div*/
List<WebElement> cals=driver.findElements(By.xpath("//div[@class='monthBlock first']//tr"));
System.out.println(cals.size());
/*iterating the "tr" list*/
for( WebElement daterow : cals){
/*getting the all "td" s*/
List<WebElement> datenums = daterow.findElements(By.xpath("//td"));
/*iterating the "td" list*/
for(WebElement date : datenums ){
/* Checking The our input Date(if it match go inside and click*/
if(date.getText().equalsIgnoreCase(parts[0])){
date.click();
break;
                      }
                 }
             }
}

// This method will return Month Number
public  int getMonthNum(String month){
for (Month mName : Month.values()) {
if(mName.name().equalsIgnoreCase(month))
return mName.value;
}
return -1;
}

// Here I am Creating Enum Method(I am assigning Number to every Month)
public enum Month {
January(1), February(2), March(3), April(4), May(5), June(6) , July(7), August(8), September(9), October(10), November(11),December(12);
private int value;

private Month(int value) {
this.value = value;
}

}

  @After
public void tearDown() throws Exception {
driver.quit();
}



}

Saturday, 22 October 2016

Getting total no.of Checkboxes/Textboxes/Dropdowns/iframes/Links on a web page

Getting total no.of Checkboxes/Textboxes/Dropdowns/iframes/Links on a web page



In one of the Previous Post we had details about WebDriver findElements() method.
 This is very useful to find the total no.of  desired elements on a wepage .

Here are some of the examples :

Getting total no.of Links on a Webpage :
Here is the sample code to get the total no.of links on facebook registration page:


Getting total no.of checkboxes on a Webpage :
Here is the sample code to get the total no.of checkboxes on facebook registration page:

driver.get("http://facebook.com");
List<webelement> checkboxes=driver.findElements(By.xpath("//input[@type='checkbox']"));
System.out.println("total checkboes "+checkboxes.size());
</webelement>


Getting total no.of dropdown menus on a Webpage :
Here is the sample code to get the total no.of dropdown menus on a facebook registration page:

driver.get("http://facebook.com");
List<webelement> dropdown=driver.findElements(By.tagName("select"));
System.out.println("total dropdown lists "+dropdown.size());
</webelement>

Getting total no.of textboxes on a Webpage :
Here is the sample code to get the total no.of textboxes on facebook registration page:

driver.get("http://facebook.com");
List <webelement> textboxes=driver.findElements(By.xpath("//input[@type='text'[@class='inputtext']"));
System.out.println("total textboxes "+textboxes.size());
</webelement>

Here is the sample code to get the total no.of textboxes on hotmail registration page:

driver.get("https://signup.live.com");
List <webelement> totalTextboxes=driver.findElements(By.xpath("//input[@type='text']"));
System.out.println("total textboxes "totalTextboxes.size());
</webelement>

Getting total no.of iframes on a Webpage :
Here is the sample code to get the total no.of iframes :

driver.get("https://www.facebook.com/googlechrome/app_158587972131");
List <webelement> totaliFrames=driver.findElements(By.tagName("iframe"));
System.out.println("total links "+totaliFrames.size());
</webelement> 

Read background color of an element


Code For Backgroud color of an element
driver.get("http://www.google.co.in/"); String color = driver.findElement(By.name("btnK")).getCssValue("background-color"); System.out.println("The background color of Google search button"+color);















Friday, 21 October 2016

Download And Save Image

Download And Save Image Using Selenium WebDriver + Actions + Robot (1)

Interaction API tutorial section. For downloading Image, We will use same WebDriver Actions class with java robot class.
For saving Image from web page In selenium webdriver, We have to perform bellow given actions.

    Right click on Image
    Select "Save Image As" option from mouse right click context menu.
    Enter file name In save Image dialog
    Press Save button.

Right click on Image using contextClick() method of Actions class
As you know, "Save Image As" option will display when you right click on any Image. We will use contextClick() method of WebDriver Actions class to right click on Image as shown In bellow Image.

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Actions_Test {

 WebDriver driver;
 @BeforeTest
 public void setup() throws Exception {
  driver =new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.get("http://any website");
 }

 @Test
 public void Save_Image() throws IOException, InterruptedException, AWTException {
  //Locate Image
  WebElement Image =driver.findElement(By.xpath("//img[@border='0']"));
  //Rihgt click on Image using contextClick() method.
  Actions action= new Actions(driver);
  action.contextClick(Image).build().perform();

  //To perform press Ctrl + v keyboard button action.
  action.sendKeys(Keys.CONTROL, "v").build().perform();

  Thread.sleep(3000);
  Robot robot = new Robot();
  // To press D key.
  robot.keyPress(KeyEvent.VK_D);
  // To press : key.
  robot.keyPress(KeyEvent.VK_SHIFT);
  robot.keyPress(KeyEvent.VK_SEMICOLON);
  robot.keyRelease(KeyEvent.VK_SHIFT);
  // To press \ key.
  robot.keyPress(KeyEvent.VK_BACK_SLASH);
  // To press "test" key one by one.
  robot.keyPress(KeyEvent.VK_T);
  robot.keyPress(KeyEvent.VK_E);
  robot.keyPress(KeyEvent.VK_S);
  robot.keyPress(KeyEvent.VK_T);
  // To press Save button.
  robot.keyPress(KeyEvent.VK_ENTER);
 }
}
}

Windows Handling in selenium webdriver


Selenium WebDriver assigns an alphanumeric id to each window as soon as the WebDriver object is instantiated. This unique alphanumeric id is called window handle. Selenium uses this unique id to switch control among several windows.

package com.windowshandling;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Windows_Handle {
public static WebDriver d;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "d://chromedriver.exe");
d=new ChromeDriver();
d.navigate().to("https://www.facebook.com");
d.manage().window().maximize();
String mainwindow=d.getWindowHandle();
System.out.println("unique id for mainwindow:::"+mainwindow);
d.findElement(By.linkText("Terms")).click();
Set<String>windows=d.getWindowHandles();

for(String eachwindow:windows){
System.out.println("window id is:::"+windows);
if(!mainwindow.equals(eachwindow))
{
d.switchTo().window(eachwindow);
System.out.println("subwindow title is::"+d.getTitle());
d.findElement(By.xpath(".//*[@id='email']")).sendKeys("testing@gmail.com");
d.findElement(By.xpath(".//*[@id='pass']")).sendKeys("test12345");
d.findElement(By.xpath(".//*[@id='u_0_0']")).submit();

d.switchTo().window(mainwindow);
System.out.println("title is::"+d.getTitle());
d.findElement(By.xpath(".//*[@id='email']")).sendKeys("testing@gmail.com");
d.findElement(By.xpath(".//*[@id='pass']")).sendKeys("test12345");
d.findElement(By.xpath(".//*[@id='u_0_0']")).submit();
String text=d.findElement(By.xpath(".//*[@id='globalContainer']/div[3]/div/div/div/div[2]/a")).getText();
System.out.println("message is::"+text);
      }
       }
    }
}

Compare Strings Examples in java


package com.methods;
public class String_Functions {
public static void main(String[] args) {
String Str1="iam learning selenium";
String str2="   iam lazy to practise";
//equals function
System.out.println("comapring two styrings::"+Str1.equals(str2));
//concat function
System.out.println("Concatenation two strings:::"+Str1.concat(str2));
//charAt function
String st1="iam so beautifull";
System.out.println("index of charaAT:::"+st1.charAt(5));
//length function
System.out.println("lenght of st1::"+st1.length());
//toLowerCase function
String s="sELeNIuM";
System.out.println("LOWERCASE::"+s.toLowerCase());
//toUpperCase function
String s1="SEleIuM";
System.out.println("LOWERCASE::"+s1.toUpperCase());
//indexOf function
String t="iam very happy";
System.out.println("index of:::"+t.indexOf("very"));
//valueOf function
int j=100;
System.out.println("convert int to string::"+String.valueOf(j));
//parseInt function
String i="200";
System.out.println("convert string to int::"+Integer.parseInt(i));
//substring function
String st="i want job without practise";
System.out.println("substring is:::"+st.substring(11, 18));
//substring function
String p="RS/-300/-";
System.out.println("price substring is:::"+p.substring(4,7));
//split function
String splt="HCL@INFOSYS@DELOITE@IBM@GOOGLE@TECH";
String arrayvar[]=splt.split("@");
for(String each:arrayvar){
System.out.println("each index::"+each);
}
//split function
String sn="i want job in top mnc but i will not be regualr to class";
String var[]=sn.split(" ");
for(String eachindex:var){
System.out.println("index is::"+eachindex);
}
//trim function
String tr="                    testing tools                ";
System.out.println("trim vallue is::"+tr.trim());

}

}

Comparing Strings:
In order to compare Strings for equality, you should use the String object's equals or equalsIgnoreCase
 methods.

For example, the following snippet will determine if the two instances of String are equal on all
 characters
String firstString = "Test123";
String secondString = "Test" + 123;
if (firstString.equals(secondString)) {
   // Both Strings have the same content.
}
This example will compare them, independent of their case


import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
            public static void main (String[] args) throws java.lang.Exception
            {
                        String firstString = "Test123";
                        String secondString = "TEST123";
                        if (firstString.equalsIgnoreCase(secondString)) {
                           System.out.print("Equal");
                        }
            }
}

Comparing Strings in switch statement

String stringToSwitch = "A";
switch (stringToSwitch) {
    case "a":
        System.out.println("a");
        break;
    case "A":
        System.out.println("A"); //the code goes here
        break;
    case "B":
        System.out.println("B");
        break;
    default:
        break;
}

Changing the case of characters within a String


The String type provides two methods for converting strings between upper case and lower case:

toUpperCase to converts all characters to upper case
toLowerCase to convert all characters to lower case
These methods both return the converted strings as new String instances:
the original String objects are not modified.
String string = "This is a Random String";
String upper = string.toUpperCase();
String lower = string.toLowerCase();

System.out.println(string);   // prints "This is a Random String"
System.out.println(lower);    // prints "this is a random string"
System.out.println(upper);    // prints "THIS IS A RANDOM STRING"


Finding a String Within Another String

To check whether a particular String a is being contained in a String b or not, we can use the method
 String.contains() with the following syntax:

b.contains(a); // Return true if a is contained in b, false otherwise
The String.contains() method can be used to verify if a CharSequence can be found in the String.
The method looks for the String a in the String b in a case-sensitive way.

String str1 = "Hello World";
String str2 = "Hello";
String str3 = "helLO";

System.out.println(str1.contains(str2)); //prints true
System.out.println(str1.contains(str3)); //prints false


Reversing Strings

There are a couple ways you can reverse a string to make it backwards.

StringBuilder/StringBuffer:

String code = "code";
 System.out.println(code);

 StringBuilder sb = new StringBuilder(code);
 code = sb.reverse().toString();
Char array:
String code = "code";
System.out.println(code);

char[] array = code.toCharArray();
for (int index = 0, mirroredIndex = array.length - 1; index < mirroredIndex; index++, mirroredIndex--) {
    char temp = array[index];
    array[index] = array[mirroredIndex];
    array[mirroredIndex] = temp;
}

// print reversed
System.out.println(new String(array));

 System.out.println(code);