XPath in Appium: Tutorial

Xpath is a great way to locate elements. Here’s how to use XPath in Appium for locating elements and automating them for testing.

Guide Banner Image
Home Guide XPath in Appium: Tutorial

XPath in Appium: Tutorial

Locating UI elements accurately is one of the most critical parts of mobile test automation. In Appium, testers often rely on XPath, an XML-based locator strategy, to identify elements when IDs or accessibility labels aren’t available. While XPath is powerful and flexible, it also comes with performance trade-offs.

Overview

What is XPath in Appium?

  • XML Path Language used to navigate XML structures and locate UI elements.
  • Supports path-like syntax for traversing components in native, hybrid, or web apps.
  • One of Appium’s locator strategies alongside ID, class name, and accessibility ID.

Advantages and Limitations of XPath Locators

  • Advantages: 200+ built-in functions, handles text-based locators, solves complex element searches.
  • Limitations: Slower than ID or accessibility ID, fragile with UI changes, harder to maintain.

How to Use XPath in Appium Tests

  • Setup: Start Appium server, define desired capabilities, and connect to BrowserStack App Automate.
  • Upload & Run: Upload app (APK/IPA) → set device/OS → initialize remote driver.
  • Element Location: Use MobileBy.XPATH with conditions like content-desc, text, or resource-id.
  • Validation: Perform clicks, enter inputs, assert results, and close session with driver.quit().

Best Practices for XPath in Appium

  • Use XPath as a fallback when unique IDs are not available.
  • Prefer faster locators (ID, accessibility ID) for stable and maintainable scripts.
  • Always validate XPath selectors on real devices to ensure accuracy.

This article explains XPath in Appium, its strengths and drawbacks, how to implement it in scripts, and best practices for reliable mobile test automation.

What is XPath?

Before getting into the specifics, it is necessary to understand what exactly an XPath is and how it helps as a locator.

XPath is nothing but XML Path or an expression language that is used to query or transform XML documents. The XPath consists of the following properties:

  1. One of the many ways to locate UI elements in web or mobile applications
  2. Xpath is a World Wide Web consortium recommendation.
  3. Xpath has a path-like syntax that helps in navigating through the UI elements of an application.

Even though Xpath is one of the locators for UI elements, it is not one of the conventional choices of many Quality Assurance professionals or Mobile/Web app testing professionals. Let’s examine some of the advantages and disadvantages of using Xpath in testing.

Advantages and Limitations of using XPath

Advantages of using XpathLimitations of using Xpath
Built-in Functions – XPath comes with around 200 built-in functions for string values, boolean values, etc.If the UI elements of the application constantly change during development. The XPath makes the changes expensive with each build.
Xpath allows you to create selectors for complex problems where you can search for elements where only the text is available.Xpath is untidy and slow compared to other locators for UI elements in an application.

How do you use Xpath in Appium?

In a conventional setting, you may have to go through the following steps – not necessarily in the exact order.

  1. Getting the Appium server started
  2. Creating the desired capabilities
  3. Choosing the environment, OS, etc.
  4. Starting up the Emulator through the Android App
  5. Creating a test script in a different environment
  6. And making sure all the system dependencies and test dependencies are already installed and running.

Note: Sometimes unforeseen circumstances or mere slight system dependencies can significantly hinder running a simple Appium script.

To avoid this, you can simply use Browserstack App Automate by following the steps written below.

Step 1 Download a sample app, or you can also upload your own application. Using the following Python script.

[python]

import requests




files = {

    'file': open(r'C:\Users\waseem k\Downloads\WikipediaSample.apk', 'rb'),

}




response = requests.post('https://api-cloud.browserstack.com/app-automate/upload',

                         files=files,

                         auth=("mohammadwaseem_r3b75X", "JxCJvHgZM5cxPrir6zHS"))




print(response.content)





[/python]

Uploading APK file to test on BrowserStack App Automate using Python

Step 2 The output will give you a URL for the application that you have uploaded. You will use that URL in the script given below to run a sample build using Appium and Xpath.

Step 3 Use the following Python Script to run the Appium test using Xpath.

[python]

from appium import webdriver

from appium.webdriver.common.mobileby import MobileBy

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

import time




desired_cap = {

    # Set your access credentials

    "browserstack.user": "",

    "browserstack.key": "",




    # Set URL of the application under test

    "app": "bs://c700ce60cf13ae8ed97705a55b8e022f13c5827c",




    # Specify device and os_version for testing

    "device": "Google Pixel 3",

    "os_version": "9.0",




    # Set other BrowserStack capabilities

    "project": "First Python project",

    "build": "browserstack-build-1",

    "name": "first_test"

}




[/python]

Python Script to run appium test using Xpath

Note: You will need to install dependencies like Appium in Python and describe the desired capabilities as shown in the script.

Step 4 The sample test will install the application on the device and search for the keyword given in the script. And in the end, add Asserts for the results in the list.

[python]

# Initialize the remote Webdriver using BrowserStack remote URL

# and desired capabilities defined above

driver = webdriver.Remote(

    command_executor="http://hub-cloud.browserstack.com/wd/hub",

    desired_capabilities=desired_cap

)




# Test case for the BrowserStack sample Android app.

# If you have uploaded your app, update the test case here.

search_element = WebDriverWait(driver, 30).until(

    EC.element_to_be_clickable((MobileBy.XPATH, "(//*[(@content-desc='Search Wikipedia')])[1]"))

)

search_element.click()

search_input = WebDriverWait(driver, 30).until(

    EC.element_to_be_clickable((MobileBy.XPATH, "(//*[(@text='Search Wikipedia')])[1]")

))

search_input.send_keys("Browserstack")

time.sleep(5)

search_results = driver.find_element_by_xpath("//*[(@resource-id='org.wikipedia.alpha:id/page_list_item_container')])")

assert (len(search_results) > 0)

# Invoke driver.quit() after the test is done to indicate that the test is completed.

driver.quit()




[/python]

Step 5 You can display the results in the dashboard, as seen below.

Xpath in Appium Test ResultAs you can see, the logs show how the application was launched, and one of the elements was located using the XPath.

Conclusion

There is no hard and fast rule for using any specific selector to locate a UI element in a web or mobile application. So is the case with Xpath, be it in Appium or selenium. As a wise QA professional, you must always rely on project requirements and, based on those, create your testing strategies. Even though XPath in test scripts may not be a wise choice in the QA community, Appium saves the day.

Tags
Appium Mobile App Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord