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

}












5 comments:

  1. What is the precedence followed while using the locators?

    ReplyDelete
    Replies
    1. I cannot understand your question sorry for that.do you want to know that what is the meaning of the'//','*','@' etc.In brief // means select node from the current location,'*' means all element,'@' means attributes. If want to know more about this you can please go to this link http://startingwithseleniumwebdriver.blogspot.in/

      Delete
  2. Hi!
    How can I get script in webpage from Selenium? I use Python and webdriver chrome.
    I wonder if its possible to get the same code of "inspect element" in a text mode...
    Thanks!
    danielecnomia2010@gmail.com

    ReplyDelete
    Replies
    1. You can record the script using Selenium IDE Plug-In and export it from File->Export TestCase As->Python.

      Delete
  3. This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work. Mobile Duress systems

    ReplyDelete