Cannot loop through similar elements

Hello Everyone!

I know this might be a basic question, but I’ve been stuck on this problem. I am developing an automation framework for a mobile app on android using python appium. In the app there are a lot of similar elements that have the same ids so I have to use xpath a lot and as such I have repeated myself and created a method for each element. My code is kind of a mess and I am now looking to reduce it. I have multiple test case files that share every step except for one element like this:

el  = self.driver.find_element_by_xpath("//android.widget.TextView[@text='A']")
el2 = self.driver.find_element_by_xpath("//android.widget.TextView[@text='B']")
etc for over 50 elements with the only difference being the text

my current method, which is the only step different between the test scripts, that I call from my page file to find each of the elements is:

def tapElementA(self):
     for x in range(0, 20):
            el = self.driver.find_element_by_xpath("//android.widget.TextView[@text='A']")

        except NoSuchElementException:

What I would like to do is create 1 script to loop and test each of the elements. Should I create a list, dictionary, or maybe a JSON file to reference each element? Does anyone have experience with something like this? I’m still new to python and coding in general but like I said, I’m just trying to clean up my code. Please let me know if my explanation is not clear and I will edit it accordingly.

1 Like

To answer my own question:

myList = ["element", "element", "element", ....]
for x in myList:
    (test script actions)
        el = self.driver.find_element_by_xpath("(""%s"") % x)

This will replace the ("(""%s"") % x) with the xpath, id, or whatever search method your using and will run the test script the same amount times as the number elements in your list. Please let me know if you need further explanation.