'How can I find element by non-unique resousre-id?

I test an application which use non-unique resourse-id for elements.

Is there any way to find such elements by xpath like

//*[@resourse-id='non-unique-id'][2]

I mean the second element with same resourse-id.



Solution 1:[1]

I'd recommend avoiding xpath in mobile automation since this is the most time-consuming strategy to find elements. If you don't have any other anchors for your elements but you confident in its order, you can stick to the following approach: Appium driver can return a list of elements with the same locator, in case of Page Object model you can either do this way:

@AndroidFindBy(uiAutomator = "resourceIdMatches(\".*whatever\")")
private List<MobileElement> elements;

so, once your page is initialized, you can access an element by index:

elements.get(1).click();

or, in case of manual managenemt, you can do this way:

List<MobileElement> elements = driver.findElements(MobileBy.AndroidUIAutomator("resoureceIdMatches(\".*whatever\")"));
elements.get(3).click();

Hope this helps.

Solution 2:[2]

As far as my understanding goes, you need to select the second element with the path as mentioned: //*[@resourse-id='non-unique-id']

To do that, you need to first grab all the elements with the same non-unique resource ID and then get() them. So, your code should be:

driver.findElements(By.xpath("//*[@resourse-id='non-unique-id']")).get(1).click();

The index for any list starts at 0. So, the second element can be accessed through the value of 1.

Hope this helps.

Solution 3:[3]

Try following approach:

(//*[@resourse-id='non-unique-id'])[2]

Solution 4:[4]

HTML with non-unique ids is not a valid HTML document.

So, for the sake of future testability, ask the developers to fix the ids.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yevhen Danchenko
Solution 2
Solution 3 frianH
Solution 4 Mate Mrše