Search code examples
pythonseleniumclickfindelement

Python selenium : How to do a loop to find an element and click() on it multiple time until not exist?


I have this code to find element (delete product from cart), in my case i have more then one element so i need a loop de delete the products from cart one by one, this is my code but it's not working : while(self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]')): self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]').click()


Solution

  • Your code doesn't work because you are trying to click on an array of elements (self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]').click()). Possible solution would be to use find_element_by_xpath (without the 's') when clicking.

    Or

    You should be able to do it with:

    # get all remove item buttons
    removeButtons = self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]')
    # loop over each element and click on it
    for removeButton in removeButtons:
      removeButton.click()