Search code examples
androidpythonappium

How to get the number of items in an ExpandableListView for Appium using python?


I'm trying to automate an Android app using Appium and python. I have a screen with a list view and I'd like to create a function that iterates through the list and returns the names in the list, then compares that to an expected list (alphabetization matters). I would like to use this function for screens that might have lists of different lengths, do I need to be able to determine the length of the list first.

actual_names = []
expected_names = ["Abe", "Bob", "Carl"]
for num in range(1, 4):
    xpat = "//android.widget.ExpandableListView[1]/android.widget.FrameLayout[" + str(num) + "]/android.widget.RelativeLayout[1]/android.widget.TextView[1]"
    text = appium_driver.find_element_by_xpath(xpat).text
    actual_names.append(text)

assert expected_names == actual_names

This code works, but only for one screen and only the exact number of items in the list. If the number of items in the list changes, it fails. This is very brittle. How can I improve this and make it more dynamic? I am using Python 3 and Appium 1.5.3


Solution

  • actual_names = []
    expected_names = ["Abe", "Bob", "Carl"]
    xpat = "//android.widget.ExpandableListView/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.TextView"
    elements = appium_driver.find_elements_by_xpath(xpat)
    for element in elements:
        text = element.text
        actual_names.append(text)
    
    assert expected_names == actual_names
    

    The difference here is that I'm using appium_driver.find_elements_by_xpath(), which will collect all elements that match the criteria given and give them as a list for you to look at.

    The xpath statement should not use the index numbers when you want to match against multiple elements with similar path, so I removed them.