Sunday, December 29, 2013

Some Example Of Mouse Event And KeyBoard Event With Selenium Webdriver


Now we know how to create and access Mouse and KeyBoard event with selenium webdriver. Here we try to learn how to use different method of Mose and KeyBoard.We try to learn this to solve some problem,there may be some other better solution,if any body have the better solution please comments about this ,ok lets start:

1.Sending Text into the textbox
2.Sending Capital Text into the textbox
3.Context Click
4.Select Item From Context Menu
5.Select multiple option from multi select dropdownlist consecutively 
6.Locate The Element Coordinates and do some mouse event on this element
7.Navigate To other Element using Tab Key


1.Sending Text into the textbox:

        Actions builder=new Actions(driver);
        builder.moveToElement(txtBoxElement).click(txtBoxElement)
                .sendKeys(txtBoxElement,"Test").build().perform();

Here  we observe that moveToElement(WebElement) method used to move to the webelement then click(WebElement) method to click on this element.At last  use sendKeys(WebElement,Text) method to send string value to the textbox.


2.Sending Capital Text into the textbox
       
        Actions builder=new Actions(driver);
        builder.moveToElement(txtBoxElement).click(txtBoxElement)
                .keyDown(Keys.SHIFT).sendKeys(txtBoxElement, "capitaltesT")
                .keyUp(Keys.SHIFT).build().perform();

Here  keyDown(Keys.SHIFT) method is use to hold the shift key logically and after sending the data into the webelement free this holed down key using keyUp(Keys.SHIFT). One thing keep in mind that keyDown() method only and only used with modifier keys like SHIFT,ALT,COMMAND.


3.Context Click

        Actions builder=new Actions(driver);
        builder.moveToElement(txtBoxElement)
                   .contextClick(txtBoxElement).build().perform();


 contextClick(webElement) method is used to open the context menu of an webelement.

4.Select Item From Context Menu

        Actions builder=new Actions(driver);
        builder.contextClick(txtBoxElement)
                  .sendKeys(Keys.ARROW_DOWN,Keys.ARROW_DOWN,Keys.ARROW_DOWN
                  ,Keys.ARROW_DOWN,Keys.ARROW_DOWN,Keys.ARROW_DOWN
                  ,Keys.RETURN).build().perform();

 After open the context menu of an particular webelement we go down, to the option of this menu using Keys.ARROW_DOWN parameter into the sendKeys() method. We send Keys.ARROW_DOWN as much as we go down of this menu,means if we want to select the 4 th option then send 4 Keys.ARROW_DOWN as a parameter.After that select the option from this menu using sending the Keys.RETURN as a parameter into the sendKeys() method.

5.Select multiple option from multi select dropdownlist consecutively

       Actions builder=new Actions(driver);
       WebElement multiSelectDropDown=driver.findElement(By.name("multiselectdropdown"));
       List<WebElement> dropdownlists = multiSelectDropDown.findElements(By.tagName("option"));
       builder.clickAndHold(dropdownlists.get(0))
                                         .moveToElement(dropdownlists.get(6)).release().build().perform();


Select dropdownlist item from where we start to select and then send it as an parameter of clickAndHold() method. Then choose the dropdownlist where we try to finish our selection and send this into the
moveToElement() method.We need to use release() metod to release the mouse click.

6.Locate The Element Coordinates And Some Mouse Event On This Element

      Locatable locatable = (Locatable) driver.findElement(By.id("loginbutton"));
      Mouse mouse = ((HasInputDevices) driver).getMouse();
      mouse.mouseMove(locatable.getCoordinates());
      mouse.click(locatable.getCoordinates());


7.Navigate To other Element using Tab Key

       Actions builder=new Actions(driver);
       builder.moveToElement(txtBoxElement)
                                 .sendKeys(txtBoxElement, Keys.TAB)
                                 .build().perform();

Here we moveToElement() used to jump over the element then sendKeys(txtBoxElement, Keys.TAB) method is used to move cursor or select the the elemen.




Saturday, December 28, 2013

Mouse And KeyBoard Event Handling Using Selenium WebDriver


Keyboard and Mouse are most usable peripheral devices by which we can interact with webpages.So we need some motivation to galore knowledge on this using Selenium Web Driver.

Basically we have 2 type of things to discuss:

1.Mouse Event
2.KeyBoard Event

1.Mouse Event 

Step 1:

Import Actions and Action class.

import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

Step 2: 

Create a Instance of Actions class

Actions builder=new Actions(driver);

Step 3:

Get the Action using build(),this method use to bind multiple action into a one action.

Action selectAllText=builder.moveToElement(txtBoxElement).
                                            sendKeys(txtBoxElement, "test").
                                                      doubleClick(txtBoxElement).build(); 

Here we try to send text into the web element which is a textbox field and double on it so text should be selected.
  
 Step 4:

To execute this action we need perform().

selectAllText.perform();


2.KeyBoard Event

The keyboard interactions API will (first) support keyboard actions without a provided element. The additional work to focus on an element before sending it keyboard events will be added later on.

Step 1:

Import Actions and Action class.

import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

Step 2: 

Create a Instance of Actions class

Actions builder=new Actions(driver);

Step 3:

Get the Action using build(),this method use to bind multiple action into a one action.

Action writeCapital=builder.keyDown(Keys.SHIFT).
                                      sendKeys(driver.findElement(By.name("email")),"abc").
                                              keyUp(Keys.SHIFT).build().perform();

Here we try to hold Shift key and send text, by this way we get the capital letter into the webelement field(basically it is a textbox field).

 Step 4:

To execute this action we need perform().

writeCapital.perform();

Keep in mind:

1.When  KeyDown() method use for particular key then should be release this key using keyUp() method.
2.KeyDown() method is only used for modifier keys Shift,Alt,Control

 


 

Wednesday, December 18, 2013

Accessing Different Web Element Using Selenium


Every webpage have many web elements like textbox links,checkbox,list and along with other controls.

Here we try to learn how to access web element  such as like
  • TextBox
  • RadioButton
  • CheckBox
  • ListBox
  • Link
  • Alert
  • IFrame

 1. TextBox

On previous posts we learn how to find the name,class,id,xpath,csspath etc using firebug and firepath.
 
 Here we try to give some value into the inputbox and clear the ipput field.

Entering values in Input Box 

sendKeys() method is used to enter the value into the input boxes.
driver.findElement(By.name("txtbox1")).sendKeys("Test")

Deleting Values in Input Box

clear() method is used to clear the input box.
driver.findElement(By.name("txtbox1")).clear()

Read Input Box value

It is little bit tricky, using getText() doesnot return any dynamically changed value so we need getAttribute() method to get the value or text of this input field. driver.findElement(By.name("txtbox1")).getAttribute("value") 

Check Disabled or ReadOnly InputBox 

 isEnabled() method is used to check the inputbox.

.

       
Example Code
        WebElement element = driver.findElement(By.name("txtbox1"));
        element.sendKeys("Test");

        if (driver.findElement(By.name("txtbox2")).isEnabled()) {
            driver.findElement(By.name("txtbox2")).sendKeys("abcd");
        }
        if (!element.getAttribute("value").isEmpty()) {
            element.clear();
            element.sendKeys("field cleared but again put some value");
        }

2.RadioButton

Toggling on a radio button is done by click().Get the value or text of this radiobutton field we can use getAttribute() method .



Example Code
        List<WebElement> elements = driver.findElements(By.name("radioGroup1"));
             for (WebElement e : elements) {
                 System.out.println(e.getAttribute("value").toString());
                     if (e.getAttribute("value").equals("Radio Button 4 Selected")) {
                         e.click();
            }
        }
 

3.  CheckBox

Toggling checkbox on/off using click() method.Get the value or text of this checkbox field we can use getAttribute() method .We can also verify the checkbox on/off by isSelected() method.



Example Code
        List<WebElement> elements = driver.findElements(By.name("chkbox"));
        for (WebElement e : elements) {
            System.out.println(e.getAttribute("value").toString());
            if (e.getAttribute("value").equals("Check Box 4 Selected")) {
                            if(!e.isSelected()){
                                      e.click();
                            }
            }
        }

 

4.ListBox

A.Single Select List.
B.Multiple Select List.

A.Single Select List


At most one item can be selected in this type of list.

We access this list in two way
1. Import "import org.openqa.selenium.support.ui.Select".
2.Declare the drop-down element as an instance of the Select class. In the example below, we named this instance as “listboxelements”.
3.We can now start controlling “listboxelements” by using any of the available Select methods like:
        listboxelements.selectByIndex(4);
        listboxelements.selectByVisibleText("Item 8");
        listboxelements.selectByValue("Item 7");
4.Get the text value of this selected list by using listboxelements.getFirstSelectedOption().getText()



Example Code
        WebElement dropdownlist = driver.findElement(By.name("dropdownlist"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
        listboxelements.selectByVisibleText("Item 8");
        listboxelements.selectByValue("Item 7");
        System.out.println(listboxelements.getFirstSelectedOption().getText());
or
        WebElement singleSelectDropDown=driver.findElement(By.name("dropdownlist"));
        List<WebElement> dropdownlists = singleSelectDropDown.findElements(By.tagName("option"));
        for (WebElement webElement : dropdownlists) {
            System.out.println(webElement.getText());
                    
            if (webElement.getText().equals("Item 2")) {
                webElement.click();
            }
        }

 

B.Multiple Select List

1.It is same as Single select List
2.We can check the list allow multiple selection or not using isMultiple() method. 
3.Deselect the element we can use this methods like
        listboxelements.deselectAll();
        listboxelements.deselectByIndex();
        listboxelements.deselectByValue();
        listboxelements.deselectByVisibleText();




Example Code
        WebElement dropdownlist = driver.findElement(By.name("multiselectdropdown"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
       
        if (listboxelements.isMultiple()) {
            listboxelements.selectByVisibleText("Item 8");
            listboxelements.selectByValue("Item 4");
        }
       
        if (listboxelements.isMultiple()){
        listboxelements.selectByValue("Item 7");
        }
        listboxelements.deselectAll();
        listboxelements.deselectByIndex(5);
        listboxelements.deselectByValue("Item 8");
        listboxelements.deselectByVisibleText("Item 8");
Or
        WebElement multiSelectDropDown=driver.findElement(By.name("multiselectdropdown"));
        Select options=new Select(multiSelectDropDown);
                    for (WebElement element : options.getOptions()) {
                           if (element.getText().equals("Item 2")) {
                               element.click();
            }
}

5.Link

Links can be accessed using an exact or partial match of their link text. So we can devide this as
A.Exact Link Text
B.Partial Link Text    

both are accessed by using the click() method.

A.Exact Link Text


Accessing links using their exact link text is done through the By.linkText() method.

Keep in Mind:
1.It is case sensitive.
2.Default it take the firstlink



Example Code

        WebElement element = driver.findElement(By.linkText("Google"));
        element.click();

B.Partial Link Text 

Accessing links using a portion of their link text is done using the By.partialLinkText() method.

Keep in Mind:
1.It is case sensitive.
2.Default it take the first matching link.


Example Code

        WebElement element = driver.findElement(By.partialLinkText("Yahoo"));
        element.click();

6.Alert

Basically Java Script alerts are 3 Type.
A.Alert
B.Confirmation
C. Prompt

A.Alert Handling


Normal JavaScript alert can be accepted by using accept() method .Get the text from this alert we use getText() method.

Example Code
        driver.findElement(By.name("alertbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();

B.Confirmation

Confirmation alert can be accepted by using accept() method or to close this alert use dismiss() method.Get the text from this alert we use getText() method.

   

Example Code

         driver.findElement(By.name("confirmbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();
        //myalert.dismiss();

C.Prompt

Prompt alert can be accepted by using accept() method or to close this alert use dismiss() method.Get the text from this alert we use getText() method and enter some text into it we use sendKeys() method


Example Code

        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.sendKeys("Test Prompt Alert JavaScript");
        myalert.accept();
        //myalert.dismiss();

7.IFrame

IFrame is use to show different page  into the same page.Now how to access frames?

1.First Locate the frame name.
2.then use switchTo() method to navigate into the iframe like:

driver.switchTo().frame(1);
driver.switchTo().frame("iframe_b");
driver.switchTo().frame(driver.findElements(By.tagName("iframe")).get(1));

If we need to switch to the parent frame then use :

driver.switchTo().defaultContent();


 


Details code is given below

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package seleniumwebdriver;

/**
 *
 * @author Administrator
 */
import java.util.List;
import java.util.logging.Logger;
import org.openqa.selenium.Alert;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;

/**
 * @author array
 *
 */
public class Test {

    /**
     * @param args
     */
     private static final Logger logger = Logger.getLogger(Test.class.getName());
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        WebDriver driver = new FirefoxDriver();
        driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
        // textbox(driver);
        // radioButton(driver);
        // checkBox(driver);
        // singleSelect(driver);
        // multipleSelect(driver);
        // linkCheck(driver);
        // partialLink(driver);
        // clickAlert(driver);
        // clickConfirm(driver);
        // clickPrompt(driver);

        // iFrame(driver);
    }

    public static void textbox(WebDriver driver) {
        WebElement element = driver.findElement(By.name("txtbox1"));
        element.sendKeys("Test");

        if (driver.findElement(By.name("txtbox2")).isEnabled()) {
            driver.findElement(By.name("txtbox2")).sendKeys("abcd");
        }
        if (!element.getAttribute("value").isEmpty()) {
            element.clear();
            element.sendKeys("field cleared but again put some value");
        }

    }

    public static void radioButton(WebDriver driver) {
        List<WebElement> elements = driver.findElements(By.name("radioGroup1"));

        for (WebElement e : elements) {
            System.out.println(e.getAttribute("value").toString());
            if (e.getAttribute("value").equals("Radio Button 4 Selected")) {
                e.click();

            }
        }

    }

    public static void checkBox(WebDriver driver) {
        List<WebElement> elements = driver.findElements(By.name("chkbox"));
        for (WebElement e : elements) {
            System.out.println(e.getAttribute("value").toString());
            if (e.getAttribute("value").equals("Check Box 4 Selected")) {
                if (!e.isSelected()) {
                    e.click();
                }

            }
        }

    }

    public static void singleSelect(WebDriver driver) {
//        WebElement singleSelectDropDown = driver.findElement(By.name("dropdownlist"));
//        List<WebElement> dropdownlists = singleSelectDropDown.findElements(By.tagName("option"));
//        for (WebElement webElement : dropdownlists) {
//            System.out.println(webElement.getText());
//            if (webElement.getText().equals("Item 2")) {
//                webElement.click();
//            }
//        }
        WebElement dropdownlist = driver.findElement(By.name("dropdownlist"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
        listboxelements.selectByVisibleText("Item 8");
        listboxelements.selectByValue("Item 7");
        System.out.println(listboxelements.getFirstSelectedOption().getText());

    }

    public static void multipleSelect(WebDriver driver) {
//                WebElement singleSelectDropDown=driver.findElement(By.name("multiselectdropdown"));
//        Select options=new Select(singleSelectDropDown);
//                    for (WebElement element : options.getOptions()) {
//                        System.out.println(element.getText());
//                           if (element.getText().equals("Item 2")) {
//                element.click();
//            }
//                    }
       
        WebElement dropdownlist = driver.findElement(By.name("multiselectdropdown"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
       
        if (listboxelements.isMultiple()) {
            listboxelements.selectByVisibleText("Item 8");
        }
       
        if (listboxelements.isMultiple()){
        listboxelements.selectByValue("Item 7");
        }
        listboxelements.deselectAll();
        listboxelements.deselectByIndex(5);
        listboxelements.deselectByValue("Item 8");
        listboxelements.deselectByVisibleText("Item 8");
       
    }

    public static void linkCheck(WebDriver driver) {
        WebElement element = driver.findElement(By.linkText("Google"));
        element.click();

    }

    public static void partialLink(WebDriver driver) {
        WebElement element = driver.findElement(By.partialLinkText("Yahoo"));
        element.click();
    }

    public static void clickAlert(WebDriver driver) {
        driver.findElement(By.name("alertbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();
       // myalert.dismiss();
       
    }

    public static void clickConfirm(WebDriver driver) {
        driver.findElement(By.name("confirmbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();
        //myalert.dismiss();
   
    }

    public static void clickPrompt(WebDriver driver) {
        driver.findElement(By.name("promptbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.sendKeys("Test Prompt Alert JavaScript");
        myalert.accept();
        //myalert.dismiss();
       
    }

    public static void iFrame(WebDriver driver){
          WebDriver frame =driver.switchTo().frame(driver.findElements(By.tagName("iframe")).get(2));
          frame.switchTo().frame("navbar-iframe");
          frame.findElement(By.name("q")).sendKeys("Test");
          //We switch to iframe 2 from current iframe
          frame.switchTo().defaultContent();
          frame.switchTo().frame(2);
          frame.findElement(By.linkText("Learn HTML")).click();
    }
}

 

Friday, December 6, 2013

Test Web Page For Selenium Web Driver

This is the Selenium Web Driver Test Page

This is the sample input box

This is the Enable Input Box:
This is the Disable Input Box:

This is the sample Radio Button

Radio Button 1
Radio Button 2
Radio Button 3
Radio Button 4

This is the sample Checkbox

Check Box 1
Check Box 2
Check Box 3
Check Box 4

This is the sample Drop Down List

Single Selection From Drop Down List

This is the sample Multi selected Drop Down List

Multiple Selection From Drop Down List
IframeTest

This is the sample Link Test

This is the sample POP UP

Simple Alert Box Message
Simple Confirm Box Message
Simple Prompt Box Message

This is the sample File Download Link

Wednesday, December 4, 2013

Locating UI Element and Use in Selenium WebDriver


Here we try to learn how to use UI element in Selenium WebDriver and how to locate.....

We can locate web element using id,classname,name,tagname,xpath,css etc........



  • Locating web element using By.id()

This is the mostly use to locate an element. But keep in mind this things

1.It should be unique.
2.It should not be auto generated.

Q.How we can verify this two features?
Ans
1.We search this Id for entire page from firebug search field.This is shown on the right corner of the firebug.
2.We reload the page every time and observe element id is changed or not.  

How to find Id of a web element

1.Open Firebug in FireFox browser.
2.Go to web element which you want to inspect and Right Click on it and select Inspect Element With Firebug  or Click the button beside the bug icon and go to the web element which you want click on it.

Here we do this things on Google search webpage.


Now we pass this value to the Selenium Web Driver like this

WebElement element = driver.findElement(By.id("gbqfq"));


  • Locating web element using By.className()

This is used if there are many DOM elements with the same class name, thus finding multiple elements becomes the more practical option over finding the first element.

This is the mostly use to locate an element. But keep in mind this things:

 1.ClassName should not hold and space within it.If present web driver show an error like "Compound class names are not supported" for this situation we should use CSS locator,We will know later about this.

How to find Class of a web element

1.Open Firebug in FireFox browser.
2.Go to web element which you want to inspect and Right Click on it and select Inspect Element With Firebug  or Click the button beside the bug icon and go to the web element which you want click on it.

Here we do this things on Google search webpage.


Now we pass this value to the Selenium Web Driver like this

WebElement element = driver.findElement(By.className("gbqfif"));


  • Locating web element using By.name()

From a test automation standpoint, whenever id is not available/ usable, we should try to use the name instead.
Name attributes don’t have to be unique in a page. If there are multiple elements with the same name, then the first element in the page is selected. 

How to find name of a web element

1.Open Firebug in FireFox browser.
2.Go to web element which you want to inspect and Right Click on it and select Inspect Element With Firebug  or Click the button beside the bug icon and go to the web element which you want click on it.

Here we do this things on Google search webpage.


Now we pass this value to the Selenium Web Driver like this

WebElement element = driver.findElement(By.name("q"));


  • Locating web element using By.tagName()

It is useful when we try to locate a web element using DOM tag name

Pros:
1.It actually will search and return an array of all the tables with the specified tag name .
2.Go for tag only if id ya class is not specified

Cons:
1.It is slow.
2.It is not more specific. 

How to find tagname of a web element

1.Open Firebug in FireFox browser.
2.Go to web element which you want to inspect and Right Click on it and select Inspect Element With Firebug  or Click the button beside the bug icon and go to the web element which you want click on it.

Here we do this things on Google search webpage.


Now we pass this value to the Selenium Web Driver like this

List<WebElement> listelements = driver.findElements(By.tagName("input"))
or
WebElement element = driver.findElements(By.tagName("input"));



  • Locating web element using By.xpath()

It is useful when identifier is dynamically generated.

Pros:
1. XPath is a very powerful language to express which element to identify.
2.If we can use it correctly, it can produce very reliable and low maintenance locators

Cons:
1.If we use it incorrectly, it can create very brittle test cases.
2.They are often the slowest, especially in older versions of IE! .Few times slower than ids or names.

How to find xpath of a web element

We learn in previous post how to get xpath of an element using FirePath.Here we get this using Firebug

1.Open Firebug in FireFox browser.
2.Go to web element which you want to inspect and Right Click on it and select Inspect Element With Firebug  or Click the button beside the bug icon and go to the web element which you want click on it.
3.Right Click on the the below Html code and select "Copy XPath"

Here we do this things on Google search webpage.

Now we pass this value to the Selenium Web Driver like this

WebElement element = driver.findElement(By.xpath("//*[@id='gbqfq']"));
WebElement element = driver.findElement(By.xpath("//*[@id="gbqfq"]"));

NB: 
1.If our xpath contains any "." before starting the expression please drop this if not then script will fail. This "." will come when we get this xpath from FirePath.
2.If we use Eclipse for selenium automation xpath element should be in single quote.If we use NetBeans then double quote for xpath element.


  • Locating web element using By.cssSelector()

According to Ashley Wilson's report from sauce labs:
Pros:
  1. They’re faster
  2. They’re more readable
  3. CSS is jQuery’s locating strategy
There was some statistics
image from cause lab's web site

Cons:
  1.No "bottom up" navigation.

How to find CSS Selector of a web element

1.Open FirePath in FireFox browser.
2.Select CSS from FirePath dropdown list.
2.Click the button beside the bug icon and go to the web element which you want click on it.

Here we do this things on Google search webpage.
WebElement element = driver.findElement(By.cssSelector("#gbqfq"));


Here we write some example code


/**
 *
 */
package mypackage;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.By.ById;
import org.openqa.selenium.By.ByName;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;


public class AccessWebElement {
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        WebDriver driver = new FirefoxDriver();

       
// And now use this to visit Google
        driver.get("http://www.google.com");
  
        // Alternatively the same thing can be done like this
        // driver.navigate().to("http://www.google.com");

      
  // Find the text input element by its id
        //WebElement element = driver.findElement(By.id("gbqfq"));
       
       
// Find the text input element by its className
        //WebElement element = driver.findElement(By.className("gbqfif"));
       
       
// Find the text input element by its name
        //WebElement element = driver.findElement(By.name("q"));
        

        /*         * Find the text input element by its tagname
         *There was many input tag so store this in
         *List<WebElement> listelements then retrive
         *this element using for loop and check the
         * the proper input field after getting this
         * break this loop
                  
        List<WebElement> listelements = driver.findElements(By.tagName("input"));
        WebElement element = null;
        for (WebElement e : listelements) {
            if (e.getAttribute("id").equalsIgnoreCase("gbqfq")) {
                System.out.println("id for the identified element = "+ e.getAttribute("id"));
                element = e;
                break;
            }
        }

      */
     

        // Find the text input element by its xpath in Eclipse
        //WebElement element = driver.findElement(By.xpath("//*[@id='gbqfq']"));
       
  
      // Find the text input element by its xpath in NetBeans
        //WebElement element = driver.findElement(By.xpath("//*[@id="gbqfq"]"));
       
       
// Find the text input element by its cssSelector
        WebElement element = driver.findElement(By.cssSelector("#gbqfq"));
      
      
  // Enter something to search for
        element.sendKeys("Cheese!");

      
  // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

   
     // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
       

        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });
    

       // Should see: "cheese! - Google Search"
        System.out.println("Page title is: " + driver.getTitle());
    }

}












Thursday, November 28, 2013

Why And How to Use Firebug,FirePath


Here we learn why and how to use Firebug and FirePath from Firefox........

1.Why we need this tools for Web Automation Using Selenium Web Driver ?

Web page object can refer to any of UI (User Interface) controls that exists in a particular web page. It can be a text, button, text box, drop down, radio button or any other UI elements.

Automation test scripts exploit UI elements to simulate any user interaction that can happen in that particular page. The interaction can be a type in text box, a click of a button, a select of a drop down or radio button and so on.

It is the responsibility of automation test developer to supply intended web objects for test scripts to perform any interaction what user expects to take on that page.

We take advantage of this tools to perform object identification in easier way.

When we proceed further we learn how to feed this object to Selenium Web Driver.

2.How we use this tools ?

Firebug :

A. Open Firebug

Start Firebug from Firefox Tools -> Web Developer -> Firebug ->Open Firebug or just press F12 or view -> Firebug or click on the bug sign on the Toolbar.

 Firebug will be opened and it shown below of the Firefox, it looks like this.....



B.Identify objects using Firebug

Firebug pane will be displayed with different internal representation of web page such as HTML, CSS, DOM and so on in which it is activated. The internal representation depicts the actual implementation of web elements (UI controls) that formed the web page on which firebug is mounted. Click on each tab in firebug to see implementation of page in HTML, CSS and DOM forms.

Click on inspect icon (next to bug icon in opened firebug) to identify any elements on web page.
Now click on the web element in page it will be highlighted in web page as shown below

 Or we can directly Inspect the web element just Right click on the web element and Choose Inspect Element With Firebug from the context menu.


FirePath :

 The FirePath allows the test developers to choose among XPath, CSS or SIzzle (JQuery) of web element  and it gives out object representation result in specified form after identifying it.

A. Open FirePath

  If FirePath is installed along with Firebug then FirePath tab should be visible on Firebug when it is opened.
B.Finding XPath Using FirPath

1.Open the Firebug.
2.Open the URL like www.google.com.
2.Navigate to the FirePath tab.

3.Click on the Inspect element button right hand side of the bug icon.....
4.Click on the web element like search text input box.
5.We see the XPath expression of this web element.
6.If we select CSS from the dropdown then we get the CSS path from it.




 
We will try to go deep on XPath  as well as finding and locate web element using different approach for Selenium Web Driver.