Monday, April 1, 2013

Xpath customization

If  xpath is unable to locate the element with IDs then other ways of creating the xpath is as below :-


Let say DOM structure is as below

<div class = "items">
       <div id="slide_page1" class="page" style="display: none;">
       <div id="slide_page2" class="property_div" style="">
                    <div id="head_text">
            <div class="service_list">
            <div class="service_list">
            <div id="toggle" class="tshow">
            <div class="service_list_button">
                 <button id="page_back" class="back_button" href="#"                                      onclick="hide_slide('slide_page2','slide_page1','back_button'); return false;" tabindex="5" title="Back" type="button"></button>

               <button id="zipcode_button" class="continue_button" onclick="hide_slide('slide_page2', 'slide_page3','')" tabindex="4" title="Continue" type="button"></button>
          </div>


And you want to click on button id = zipcode_button



Typically we write the xpath as below :
driver.findElement(By.xpath("//*[@id='zipcode_button']")).click();

                                                           OR
driver.findElement(By.xpath("//*[@id='zipcode_button' and  @class='continue_button'  and @type='button']"

                                                        OR

For Hyper Linked     :- "//a[@href= '/computer-periferal']"

                                                OR
If portion of xpath is constant   :-  "// input[@id, 'linktitle']"

                                                   OR

driver.findElement(By.xpath("//*[@id='zipcode_button']")).sendKeys(Keys.ENTER);


                                                   OR

Take the id of 1st element in DOM structure and id of element on which we are performing an action
 //div[@id='slide_page4']//button[@id='zipcode_button']
In the above xpath          [@id='slide_page4'] --> Id of first element in DOM

                                    [@id='zipcode_button']-----> id of element on which we are performing an action


                                                    OR

driver.findElement(By.xpath("//div[@id='slide_page2']/div[5]/button[2]")).click();

                                                    OR



WebElement parentelement=driver.findElement(By.xpath(".//div[@class='items']"));
List<WebElement> ListOptions=parentelement.findElements(By.xpath(".//div[starts-with(@id,'slide_page')]"));
System.out.println(ListOptions.size());
WebElement childele=ListOptions.get(1);
WebElement clickbutton=childele.findElement(By.xpath(".//button[starts-with(@id,'zipcode_button')]"));
System.out.println(clickbutton.isDisplayed());
clickbutton.click();

                                              And


price of say 1st property, we can use xpath like:
//li[starts-with(@id,'summary')][position()=1]//p[@class='price']