简体   繁体   中英

find_elements_by_xpath returns None after recursive call

I have something like this:

def get_next_src(self):
    if len(self.driver.find_elements_by_xpath(xpath/to/img)) > 0:
        return self.driver.find_element_by_xpath(xpath/to/img).get_attribute("src")
    else:
        time.sleep(5) # wait until image is loaded
        self.get_next_src() # recursive call
            

I check if there is something in my xpath and then I get attribute src . However since I am iterating though gallery image sometimes doesn't load correctly so I have to wait and repeat the call.

Now whenever I get to recursive call and it calls the function again it returns None . But If I do it like this without recursive call just repeat the if statement from above:

def get_next_src(self):
    if len(self.driver.find_elements_by_xpath(xpath/to/img)) > 0:
        return self.driver.find_element_by_xpath(xpath/to/img).get_attribute("src")
    else:
        time.sleep(5) # wait until image is loaded
        # repeat the if statement from above
        if len(self.driver.find_elements_by_xpath(xpath/to/img)) > 0:
             return self.driver.find_element_by_xpath(xpath/to/img).get_attribute("src")

I get the src tag correctly.

Why do I get None by calling it recursively and get the correct src attribute when I repeat the if statement ?

def get_next_src(self):
        if len(self.driver.find_elements_by_xpath(xpath/to/img)) > 0:
            return self.driver.find_element_by_xpath(xpath/to/img).get_attribute("src")
        else:
            time.sleep(5) # wait until image is loaded
            return self.get_next_src() # recursive call

Try doing return self.get_next_src(), in your case you are just calling the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM