With the below code, I am able to remove only the first product from the cart page but not all the products
public class RemoveProductFromCart {
public static void main(String[] args) throws Exception {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://askomdch.com/account/");
driver.findElement(By.id("username")).sendKeys("testuser1");
driver.findElement(By.id("password")).sendKeys("Password@123");
driver.findElement(By.xpath("//button[@type='submit' and @name='login']")).click();
Thread.sleep(2000);
Clicking on the cart icon==>
driver.findElement(By.xpath("//div[@id='ast-desktop-header']//div[@class='ast-cart-menu-wrap']")).click();
Thread.sleep(2000);
Grouped all the items to remove into a list and then click them one by one to remove all the products==>
List<WebElement> removeList = driver
.findElements(By.xpath("//table[contains(@class,'shop_table')]//a[@class='remove']"));
for (int i = 0; i < removeList.size(); i ) {
removeList.get(i).click();
Thread.sleep(2000);
if (removeList.size() == 0) {
break;
}
}
}
}
CodePudding user response:
By removing the first product from the cart the remaining products are rearranged there so the remaining WebElements
in the removeList
list becoming stale elements.
In order to remove all the products from the cart you have to get the removeList
again after each time the product is removed and validate there are still products in the cart, as following:
WebDriverWait wait = new WebDriverWait(driver, 30);
List<WebElement> removeList = driver.findElements(By.xpath("//table[contains(@class,'shop_table')]//a[@class='remove']"));
while(!removeList.isEmpty()){
removeList.get(0).click();
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("div.blockUI.blockOverlay")));
Thread.sleep(200);
removeList = driver.findElements(By.xpath("//table[contains(@class,'shop_table')]//a[@class='remove']"));
}