Handling iOS locator with Appium more efficiently

Ivan
2 min readJul 28, 2020

Type of locator in iOS is very important. If we select the wrong locator like using a absolute XPath, this will slow Appium as it needs to traverse the long path in your case. Absolute XPath can be brittle too.

There are a few type of locators to get the element

  • Class Name
  • ID
  • XPath
  • Accessibility id
  • ios predicate string
  • ios class chain

Refer to your inspector (example Appium Inspector) on the element.

Accessible ID

If there is a accessible id , the code should be

WebElement el = driver.findElement(MobileBy.AccessibilityID("foo"));

Class Name

Class Name should be the second in line. This is effective especially if there are only 1 unique classname — like there is only 1 button in the form

MobileElement elementButton = driver.findElementsByClassName("XCUIElementTypeButton");

iOS-specific Locator Strategies

You can try the iOSClassChain. That is the next effective selector. Example

String selector = "**/XCUIElementTypeCell[`name BEGINSWITH "C"`]/XCUIElementTypeButton[10]";<br>
driver.findElement(MobileBy.iOSClassChain(selector));

Or you can try with Predicate selector.

driver.findElementsByIosNsPredicate("isWDVisible == 1");

XPath

Absolute XPath

Finally if all these options run out , you should use XPath as last resort. Avoid absolute XPath and use relative XPath.

String El1="//XCUIElementTypeApplication[@name='appName']/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[5]/XCUIElementTypeStaticText";

Relative XPath

String El1 = “//XCUIElementTypeTable[@name=‘Customer’]/XCUIElementTypeCell[5]/XCUIElementTypeStaticText”

This is less brittle than the first one although it is still dependent on a hard coded cell (5) which may still break.

Conclusion

It is important to strategise different locators to use for iOS (and Android too!) . Getting the wrong locators not only can reduce the performance of your scripts, but it can reduce maintenance and readability.

Whenever it is possible, add Accessible ID to the elements. This will make scripting much easier, faster and stable. It is unique and does not change during localization too.

Original article is in : https://www.linkedin.com/pulse/handling-ios-locator-appium-more-efficiently-ivan-tay

--

--

Ivan

I am a Software Engineer and Psychotherapist. Follow me on Linkedin at linkedin.ivantay.org