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
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 codelak– lak2016年11月25日 09:57:31 +00:00Commented Nov 25, 2016 at 9:57
-
Could you please write full codelak– lak2016年12月19日 05:21:09 +00:00Commented 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.VanderLinden– VanderLinden2017年01月20日 15:46:22 +00:00Commented 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:
driver.findElement(By.xpath("(//*[@id='menuitem'])[index]")
where index will start from 1, NOT 0
You can write Xpath using index in two different ways.
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'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'
Explore related questions
See similar questions with these tags.