Automation Using Selenium Webdriver

Monday 24 October 2016

Captcha using Selenium Webdriver Automating(Breaking)

Automating(Breaking) captcha using Selenium Webdriver

Usually most of the companies either use their own captchas or one of the third party captchas
(GooglejQuery plugins) in the user registration page of their sites .So these pages can't be
 automated fully.
Infact Captcha itself is implemented to prevent automation. As per official captcha site

A CAPTCHA is a program that  protects  websites against bots  by generating and grading tests that humans can pass but 
current computer programs cannot.

Captchas are not brakeable but there are some third party captchas that can be breakable and one of
the example for it is "jQuery Real Person" captcha . Here is the documentation  :)


Here is the sample code to brake the "jQuery Real Person" Captcha using Selenium WebDriver.

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class captchaAutomtion { 
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void Test(){ 
  //Loading jQuery Real Person Captcha demonstration page
  driver.get("http://keith-wood.name/realPerson.html");
  JavascriptExecutor js = (JavascriptExecutor) driver;
  //Setting the captcha values
  js.executeScript("document.getElementsByName('defaultRealHash')[0]
.setAttribute('value', '-897204064')");
  driver.findElement(By.name("defaultReal")).sendKeys("QNXCUL");
  //Submit the form
  driver.findElement(By.xpath(".//*[@id='default']/form/p[2]/input")).
   .submit(); 
 }

}








Getting google search auto suggestions using Webdriver(Selenium 2)

Getting google search auto suggestions using Webdriver(Selenium 2)

In the google search when we start typing any search query google will start auto suggestions. All these search suggestions are part of a WebTable. If we would like to capture all these search suggestions then we have to just iterate through the table.

Here is the sample code which will start typing "vam" and then capture all search suggestions .
import java.util.Iterator;
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.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SearchSuggestion {
 
WebDriver driver;
 
 @BeforeTest
 public void start(){
   driver = new FirefoxDriver(); 
 }
  
 @Test
  public void SearchSuggestion() {
  
  driver.get("http://google.com");
  driver.findElement(By.id("gbqfq")).sendKeys("vam");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
   WebElement table = driver.findElement(By.className("gssb_m")); 
   List rows = table.findElements(By.tagName("tr")); 
   Iterator i = rows.iterator(); 
   System.out.println("-----------------------------------------"); 
   while(i.hasNext()) { 
           WebElement row = i.next(); 
           List columns = row.findElements(By.tagName("td")); 
           Iterator j = columns.iterator(); 
           while(j.hasNext()) { 
                   WebElement column = j.next(); 
                   System.out.println(column.getText()); 
           } 
           System.out.println(""); 
            
   System.out.println("-----------------------------------------"); 
   } 
  } 
}

Here is what we will see in the browser after running the above code.





5 different ways to refresh a webpage using Selenium Webdriver

5 different ways to refresh a webpage using Selenium Webdriver

Here are the 5 different ways, using which we can refresh a webpage.There might be even more :)

There is no special extra coding. I have just used the existing functions in different ways to get
 it work. Here they are :
1.Using sendKeys.Keys method
driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);

2.Using navigate.refresh()  method
driver.get("https://accounts.google.com/SignUp");  
driver.navigate().refresh();

3.Using navigate.to() method
driver.get("https://accounts.google.com/SignUp");  
driver.navigate().to(driver.getCurrentUrl());

4.Using get() method
driver.get("https://accounts.google.com/SignUp");  
driver.get(driver.getCurrentUrl());

5.Using sendKeys() method
driver.get("https://accounts.google.com/SignUp"); 
driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");

Find All Links In a page

Find All Links
Testers might be in a situation to find all the links on a website. We can easily
do so by finding all elements with the Tag Name "a", as we know that for any
link reference in HTML, we need to use "a" (anchor) tag.

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class getalllinks
{
public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.calculator.net");
java.util.List<WebElement> links =
driver.findElements(By.tagName("a"));
System.out.println("Number of Links in the Page is " +
links.size());
for (int i = 1; i<=links.size(); i=i+1)
{
System.out.println("Name of Link# " + i - +
links.get(i).getText());
}
}
}
Output
The output of the script would be thrown to the console as shown below. Though
there are 65 links, only partial output is shown below.








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>