How to handle element not found? [cannot unpack non-iterable NoneType object]


Python 3.7
Windows 10 64Bits


I am making a script with Appium Python 3.7. My script is making a search and needs to get the search results. In some cases, it can happen there isn’t any result at all. In this particular case of no result, Python raises an exception. When it gets some results, I get a list of elements. Here is the line of code:

search_results = driver.find_elements_by_id('')

I tried many different lines of code to handle this scenario but I always get the error message:

cannot unpack non-iterable NoneType object

Here are the lines of code I tried to handle this scenario of “No results”:

if search_results:
if search_results is not None:
if len(search_results)!=0:

But it always raises an exception as it cannot find the elements ‘’.

So I tested with an Xpath search:

search_results = driver.find_elements_by_xpath("//*[contains(@resource-id, '')]")

But I get the same error.

So I tried to handle that with “Try/Exception” but due to the complexity of my program, this Try/Exception is nested inside a global Try/exception. The problem is when the exception is raised, it is the global Exception raising the error instead of the local one which supposes to handle the scenario of “No elements found”. As a result, instead of handling locally the exception, the script goes to the end of the program where there is my global exception.

I think by looking at the code, you may understand better my issue:

def search_function(driver):
        # make the search in the search field
        search_results = driver.find_elements_by_xpath("//*[contains(@resource-id, '')]")

        if search_results:
            # do some stuff

    except Exception as ex: #the local exception which supposes to be raised instead of the global one below

        print(f"{ex} --> There wasn't obviously any result for the search .")
        found_it = False

        # here some other code I would like to execute in order to carry on the execution of my script

def main():
        #do some stuff......
    except Exception as ex: #the global exception which stop the script and show the error message.
        print(f"|||{ex} --> Error with main() method!!!")
if __name__ == '__main__':

As a resume, Python is raising the main exception of the main() method instead of raising the local one in my search() function.

Do you have any idea how can I solve this problem? Does anyone can help me please?

In your ‘try’ block, can you ‘catch’ the exception? Then you can do whatever you want.