Search code examples
pythonappiumappium-androidpython-appium

How to find all elements with a dynamic content-desc using Appium?


My locator strategy is finding an element by its content-desc attribute.
I have some text views on a screen that have this contest-desc: report_description_textview_X_lines, where X is a value between 0 to 3.

How can I get all the elements that have this dynamic content-desc?

I thought of 2 ways, but I do not know how to implement them:

  1. Find all content-desc that contains the string report_description_textview_
  2. Use RegEx in place of the changing value.

Solution

  • This is what worked for me:

    I defined my element locator as: self.the_elements = '//android.widget.TextView[contains(@content-desc, "report_title_textview_") and contains(@content-desc, "_lines")]'

    Then I got all the elements with that locator and as a list. Below is how I checked for the dynamic value:

    element = self.the_elements()[i].get_attribute('content-desc')
    dynamic_number = int(title.split('_')[3])
    
    assert dynamic_number in range(1, 3), f"Invalid number"
    

    I split the content-desc of the element by the underscore character, then I took the third element after the split, which was the dynamic number of the locator.

    Then I checked that the dynamic number must be in the range of 1 and 3. If not, it raises an assertion error message.