Delivered by FeedBurner

Select Checkbox Using Position() and last() Functions In XPath In WebDriver

Selecting checkbox Is not big task In selenium webdriver If check box has ID, Name or any other proper locator. You can check It very easily using .Click() method. .Click() Is generic method and you can use It to click on any element like select radio button, check the check box or clicking on
any other element. But supposing you have a list of Items with checkbox and any checkbox do not have any Identifier then how will you select specific checkbox? NEXT POST will describe how to select checkbox from table using following-sibling and following-sibling

Solution 1 : Using Absolute XPath
Consider checkbox list given on THIS PAGE. All the checkbox have type attribute with same value checkbox. Any of them do not have any proper locator using which I can locate specific checkbox. I wants to select check box which Is located In "Cow" row. One way Is using absolute XPath as bellow.

At place of using absolute XPath, We can use functions like last() and position() In XPath to locate specific checkbox.

Read more webdriver tips and tricks on THIS PAGE.

Solution 2 : Using position() Function In XPath
In bellow given xpath, [@type='checkbox'] will locate checkbox and function [position()=3] will locate checkbox which Is located on 3rd position from top. You can change your position number as per requirement.

Solution 3 : Using last() Function In XPath
In bellow given xpath, [last()-1] function will locate 2nd last checkbox which Is for Lion.

To locate last checkbox, You can use It as bellow.

Here Is the practical webdriver example to select checkbox using position() and last() functions.
package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Checkboxpos {
 WebDriver driver;
 public void setup() throws Exception {
  driver =new FirefoxDriver();     
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 public void selectCheck(){
  //To select Cow checkbox using position() function.
  //To select Lion checkbox using last() function.
  //To select Tiger checkbox using last() function.

You can use same thing for any element to locate It from list of same Items. You can learn how to get XPath or CSS path of any element using firebug and firepath as described in THIS POST.

1 comment:

  1. thanks for this trick. There is also another shortcut for not using position

    (//*[@type='checkbox'])[2] = (//*[@type='checkbox'])[position()=2]

    we can directly use the index instead of using position()

    Also note it starts from 1 and not 0. regards