Search code examples
pythonseleniumfor-looptry-catch

How to get an element from multiple elements until it's true in python selenium using try except


I am using python Selenium.

I need to check each for 5 elements until one of them is true, then return it.

My current code :

def status(self):
    try:
        elem = self.findelement(Objects.status_1)
        if elem == True:
            print("The status is : A")

        elif self.findelement(Objects.status_2):
            print("The status is : B")

        elif self.findelement(Objects.status_3):
            print("The status is : C")

        elif self.findelement(Objects.status_4):
            print("The status is : D")

        else:
            self.findelement(Objects.status_5)
            print("The status is : E")
    
    except Exception as e:
        print(e)
        raise AssertionError("Failed to fetch the status")

Note: The Objects.status is the directory of my locators file.

I want to get the status when it finds it. It will check one by one each element and when it finds the exact element it will stop and return the element.

So my expected output is :

The status is : D

Solution

  • You can simply change findelement to findelements and it will work. findelement method throws exception in case of no element found while findelements will return a list of element matching the passed locator. So, in case of match it will be a non-empty list interpreted by Python as a Boolean True while in case of no match it will return an empty list interpreted by Python as a Boolean False.
    I hope your findelement internally applies Selenium find_element() method and findelements will implement Selenium find_elements() method.
    So, your code could be as following:

    def status(self):
            try:
                if self.findelements(Objects.status_1):
                    print("The status is : A")
    
                elif self.findelements(Objects.status_2):
                    print("The status is : B")
    
                elif self.findelements(Objects.status_3):
                    print("The status is : C")
    
                elif self.findelements(Objects.status_4):
                    print("The status is : D")
    
                elif self.findelements(Objects.status_5):
                    print("The status is : E")
    
            except Exception as e:
                print(e)
                raise AssertionError("Failed to fetch the status")