Sunday 16 June 2013

Identify elements in Selenium

             Identify element in selenium is very interesting and give good feeling if object found. Today we will discuss how to identify element.
Selenium provide following ways to identify elements in a page by
  • id
  • name
  • xpath
  • css
  • linktext
Scenario 1: Identify element by id

Sample HTML code is given below
<input id="gbqfq" class="gbqfif" type="text" value="" autocomplete="off" name="q" spellcheck="false">

id in above given code is "gbqfq", so here is how to identify it

      driver.findElement(By.id("gbqfq"));
-----------------------------------------------------------------------------------------------------------------------------------------


Scenario 2: Identify element by name
if you will notice that name("q") is also given in the code and we can identify this element by name as following..
 
    driver.findElement(By.name("q"));

-----------------------------------------------------------------------------------------------------------------------------------------

Scenario 3: Identify element by xpath
if you will notice that name("q") is also given in the code and we can identify this element by name as following..

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

         OR

        driver.findElement(By.xpath("//input[@name = 'q']"));

* If in case you have HTML code where attribute values are changing dynamically but the text associated with web-element remain unchanged. Ex:  


       Sample HTML code : <a class=":ab" id = "ab 80" name = ":xyz"> Click Me </a>
Lets say that class, id and name are getting changed every time then use following

        driver.findElement(By.xpath("//input[text() = 'Click Me']"));

* If  there is a situation where multiple web elements sharing common html code then use following.. 

       //descendant::input[@attribute = 'value'][2]
Here [2] is pointing second element.

----------------------------------------------------------------------------------------------------------------------------------------- 

Scenario 4: Identify element by CSS

<input id="gbqfq" class="gbqfif" type="text" value="" autocomplete="off" name="q" spellcheck="false">

1. If ID is given ..   
                        css=input#gbqfq

2. If class ig given
                       css=input.gbqfif 

3. And another one is
                      css=input[id = 'gbqfq']


-----------------------------------------------------------------------------------------------------------------------------------------