Search code examples
pythonandroidseleniumappium

Does calling in find_elements...().text count as the find_elements function itself?


I have code that takes all elements of a certain class and extracts a text element from it.

chatblocks = driver2.find_elements_by_class_name("android.widget.TextView")
print(chatblocks)
chatblocktext = chatblocks[-3]

I am currently receiving a StaleElementReferenceException at the 3rd line.

Does calling in the .text function in line 3 run the find_elements function again? And why doesn't this Stale error show up on line 1?

To solve this, would loading in all the text into a list at line 1 work? I attempted this:

chatblocks = driver2.find_elements_by_class_name("android.widget.TextView").text

But I received an error saying .text cannot work for list objects.


Solution

  • see line by line execution of

    chatblocks = driver2.find_elements_by_class_name("android.widget.TextView")
    print(chatblocks)
    chatblocktext = chatblocks[-3]
    
    1. find_elements would return a list, in this case it is chatblocks
    2. print the entire list, which typically should print webelements, not their .text
    3. find the third element on left side after 0.

    Now your questions :-

    Does calling in the .text function in line 3 run the find_elements function again? And why doesn't this Stale error show up on line 1?

    • No, it won't run again. it's a list in Python, so find_elements would have returned a list of webelement. at line 1, the elements are available.

    for this :

    chatblocks = driver2.find_elements_by_class_name("android.widget.TextView").text
    

    on a list you cannot do .text instead :

    for chat in driver2.find_elements_by_class_name("android.widget.TextView"):
        print(chat.text)