How To Locate Elements using selenium web driver when only Unique value is 'index'? Resource-id,Class and Package are not unique.

Below Layout taken from Android UI Automator

enter image description here

Resource-id = android:id/menuitem

Class =       android.widget.RelativeLayout

Package =     android

3 Answers 3


You can use selenium to find an array of elements that share common characteristics such as class names and etc, then indexing through this array to locate the element you want.

elementArray = webdriver.findelements(xpath / css selector);
theElement = elementArray[1];
  • can you please write x path of this code
    – lak
    Nov 25, 2016 at 9:57
  • Could you please write full code
    – lak
    Dec 19, 2016 at 5:21
  • This is a viable solution, but is not as elegant, in my opinion, as BountyHunter's answer, which includes the index in the xpath used to locate the element. Jan 20, 2017 at 15:46

You could simply write an xpath with index specified. For the example you mentioned, the xpath should look like:


where index will start from 1, NOT 0


You can write Xpath using index in two different ways.

  1. If you want to locate particular element: Ex: driver.findElement(By.xpath("(//*[@id='menuitem'])[index]"); in this case index will start from '1' and not '0'

  2. If you are writing generic Xpath using findElements and getIndex (Using loops) Ex: driver.findElements(By.xpath("//*[@id='menuitem']").get(index).getText(); in this case index will start from '0'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.