Use findElement(s) on a native app

Using the Perfecto Object Spy, you can open an application, click an element and see its full XPath.

Theoretically speaking, you can copy this XPath into a string and use it to find the element in your script, as shown in the following example:

Copy
String elementXPath =
"//hierarchy/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.ScrollView[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.TextView[1]";

List elements = driver.findElementsByXPath(elementXPath);

However, such usage in not recommended and the script will easily break.

The reason is that the infrastructure used to generate the XPath does not guarantee that the XPath will remain the same between two different executions.

Switching devices, recompiling the app (even without code changes) or reinstalling the app may generate an XPath that is similar to, but not identical with, the original one, causing the findElements command to fail.

The recommended way would be to use the element id or any other stable element identifier, or to search for a parent element and then use the relative XPath from that element.