Appium- Article #2

How To Define Xpath- Appium

Fareena Imran
3 min readMar 7, 2022

Learn Appium from Scratch.

In this article, we’re going to learn how to define Xpath in Appium. Let’s get started 👇

To define XPath, you need t open the app in UiAutomatorviewer.

How To Open UiAutomatorViewer

There are two ways to open UiAutomatorviewer.

Way #1

Open cmd → Write ‘uiautomatorviewer’, it will open the ‘Ui Automator Viewer’ App on your pc/laptop.

Way #2

Go to C: drive → Users → UserName (Fareena) → AppData → Local → Android → Sdk → tools → bin → click on ‘uiautomatorviewer’, It will open ‘Ui Automator Viewer’ App on your pc/laptop.

Ui Automator Viewer

Now, Let’s practice how to define Xpath using Ui Automator Viewer. We’re using the app that we downloaded in the previous article.

Prerequisites

  1. Open the ‘ApiDemos-debug’ app on your mobile 📱.
  2. Connect your mobile with your PC/ laptop by USB cable🔌.
  3. Click on this button that will capture the App’s screen opened on your mobile 👇

Define XPath For The Element

To define an Xpath we use a syntax that is 👇

//tagName[@attribute='value'] 

And from here you can pick the tagName, attributes, and value for all the elements. You can pick any of the attributes with value, depending on your test.

Create Xpath for Element

Now, Let’s create an Xpath for Preference element that would be

//android.widget.TextView[@text='Perference']OR//android.widget.TextView[@index='9']OR//android.widget.TextView[@resource-id='android:id/text1']

Always Use Unique Attribute otherwise it will select the first element on the page.

Case 1: If you observe by clicking on all the elements on the page, all have the same class, package, and resource-id but index and text are unique for all. So, you can select index or text to click on any element.

Case 2: If there are two objects/elements on the page that have the same class name and have no other unique attribute then how would you target that element 🤔 ❔

You can target that element by index number, Yes!!. Let’s take the example of the ApiDemos app. In this app, there is a page name “Preference/3. Preference dependencies” where there is an option called “wifi settings” that will be enabled after clicking on the check box.

But the issue is “wifi settings” element has no other attribute to target that element the only one is class but that class is the same as one other element on the same page. So, what we’ll do, we will specify a number after defining an Xpath of that element like👇

(//android.widget.RelativeLayout)[2]//here [2] indicates that there are two elements on this page but we need to target to the 2nd element[2].

If you will define Xpath such as

(//android.widget.RelativeLayout)[1]

Then this line will target the 1st element (with class name android.widget.RelativeLayout)on the page.

Follow my article to learn more about appium.

If you find this post useful, please tap 👏 button below 😊

Best of Luck 👍

--

--