0

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
Yu Zhang
9,9625 gold badges29 silver badges48 bronze badges
asked Nov 21, 2016 at 6:28

3 Answers 3

1

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];
answered Nov 21, 2016 at 9:30
3
  • can you please write x path of this code Commented Nov 25, 2016 at 9:57
  • Could you please write full code Commented 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. Commented Jan 20, 2017 at 15:46
1

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

driver.findElement(By.xpath("(//*[@id='menuitem'])[index]")

where index will start from 1, NOT 0

answered Jan 20, 2017 at 12:59
1

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'

Kate Paulk
31.5k8 gold badges56 silver badges109 bronze badges
answered Jul 2, 2019 at 8:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.