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()
Asked
Active
Viewed 1,822 times
-1

FlutterLover
- 597
- 1
- 11
- 21
1 Answers
1
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()

Arslan Sohail Bano
- 663
- 1
- 8
-
Thanks works fine now, just a question how to stop the loop if i have no element to click on it? – FlutterLover Feb 18 '22 at 21:33
-
hmmm, if you are using `while(self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]'))` then change it to `while(len(self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]')) != 0)` this will make the loop stop if there are no more elements to click on. If you are using the for loop that I suggested it should stop automatically once all elements are clicked. – Arslan Sohail Bano Feb 18 '22 at 23:00
-
Not working its doesnt click on the button – FlutterLover Feb 21 '22 at 15:06
-
can you show the updated code? – Arslan Sohail Bano Feb 23 '22 at 14:43
-
`teams = self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]') for i in teams: actionchains = ActionChains(self.driver) WebDriverWait(self.driver, 60).until( EC.visibility_of_element_located((By.XPATH, '//*[@data-testid="RemoveProductBtn_btn"]'))) i.find_element_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]').click()` – FlutterLover Feb 23 '22 at 19:38
-
It delete just the first one – FlutterLover Feb 23 '22 at 19:40
-
The `i` variable already contains the WebElement of RemoveProductBtn_btn you don't have to find the element again. Try this: `teams = self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]') for i in teams: actionchains = ActionChains(self.driver) WebDriverWait(self.driver, 60).until( EC.element_to_be_clickable(i) ) i.click()` Maybe I should change the answer so it's better formatted, let me know. – Arslan Sohail Bano Feb 24 '22 at 12:28
-
This works fine : `teams = self.driver.find_elements_by_xpath('//*[@data-testid="RemoveProductBtn_btn"]') for i in teams: actionchains = ActionChains(self.driver) WebDriverWait(self.driver, 60).until( EC.element_to_be_clickable((By.XPATH, '//*[@data-testid="RemoveProductBtn_btn"]'))) i.click()` – FlutterLover Feb 25 '22 at 15:42