如何添加 4 个畅销商品以添加到耳机 Amazon.com 购物车



>我陷入了 Amazon.com 的自动化

自动化步骤:

  1. 打开www.amazon.com网站。
  2. 在搜索框中输入文本">耳机"。按回车键
  3. 从第 1 页显示的结果中,将所有标记为">畅销书"的商品添加到购物车。

我尝试过的代码

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\****\Downloads\chromedriver_win32\chromedriver.exe");
WebDriver driver =  new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.amazon.com");
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement searchBox = wait.until(ExpectedConditions.elementToBeClickable(By.id("twotabsearchtextbox")));
searchBox.click();
searchBox.sendKeys("Headphones"+Keys.ENTER);
Actions action = new Actions(driver);
List<WebElement> bestSellers = driver.findElements(By.xpath("//span[text()='Best Seller']/ancestor::div[@class='sg-row']/following-sibling::div[@class='sg-row']/child::div[1]"));
for(int i=1;i<=bestSellers.size();i++) {
action.moveToElement(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Best Seller']/ancestor::div[@class='sg-row']/following-sibling::div[@class='sg-row']/child::div['"+i+"']")))).build().perform();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Best Seller']/ancestor::div[@class='sg-row']/following-sibling::div[@class='sg-row']/child::div['"+i+"']"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("add-to-cart-button"))).click(); 
//System.err.println(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h2[contains(text(),'Added to Cart')]"))).getText());
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.uss-o-close-icon.uss-o-close-icon-medium"))).click();
driver.navigate().back();
driver.navigate().refresh();
System.err.println("try to find next best seller item ");
}
}

它正在为所有迭代添加第一个畅销书项目。但我想将所有 4 种最畅销的产品添加到购物车。 任何帮助将不胜感激。

在下面的代码中,xpath用于获取所有畅销商品,而无需赞助(重复)商品。使用流从畅销书元素获取 href 属性。迭代畅销书导航到URL,添加到购物车并等待成功消息:

import org.openqa.selenium.support.ui.ExpectedConditions;
//...
List<WebElement> bestSellers = driver.findElements(
By.xpath("//span[text()='Best Seller']" +
"/ancestor::div[@data-asin and not(.//span[.='Sponsored'])][1]" +
"//span[@data-component-type='s-product-image']//a"));
List<String> bestSellersHrefs = bestSellers.stream()
.map(element -> element.getAttribute("href")).collect(Collectors.toList());
bestSellersHrefs.forEach(href -> {
driver.get(href);
wait.until(elementToBeClickable(By.id("add-to-cart-button"))).click();
boolean success = wait.until(or(
visibilityOfElementLocated(By.className("success-message")),
visibilityOfElementLocated(By.xpath("//div[@id='attachDisplayAddBaseAlert']//h4[normalize-space(.)='Added to Cart']")),
visibilityOfElementLocated(By.xpath("//h1[normalize-space(.)='Added to Cart']"))
));
});

似乎你错了放置增加计数i,你可以试试这个:

action.moveToElement(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//span[text()='Best Seller']/ancestor::div[@class='sg-row']/following-sibling::div[@class='sg-row']/child::div[1])[" +i +"]")))).build().perform();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//span[text()='Best Seller']/ancestor::div[@class='sg-row']/following-sibling::div[@class='sg-row']/child::div[1])[" +i +"]"))).click();

和关闭按钮,您可以使用此定位器:

wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(@class,'uss-o-close-icon uss-o-close-icon-medium') or contains(@class,'a-link-normal close-button')]"))).click();

我看每个关闭按钮都没有相同的定位器,这里也有它的挑战。

我也有类似的问题,作业如下

  1. 前往亚马逊
  2. 按单词搜索
  3. 笔记本电脑
  4. 添加第一页的所有结果,不包括折扣产品
  5. 转到购物车并检查产品是否正确

这是代码:

public static void main(String[] args) {
// Set ChromeDriver path
System.setProperty("webdriver.chrome.driver", "C:\Users\Drivers\chromedriver.exe");
// Create a new instance of the Chrome driver
WebDriver driver = new ChromeDriver();
// Step 1: Enter amazon.com and check the homepage
driver.get("https://www.amazon.com");
System.out.println("Opened Amazon homepage");
// Step 2: Search for "laptop"
WebElement searchBox = driver.findElement(By.id("twotabsearchtextbox"));
searchBox.sendKeys("laptop");
searchBox.submit();
System.out.println("Performed search for 'laptop'");
// Step 3: Add non-discounted products in stock on the first page to the cart
List<WebElement> products = driver.findElements(By.xpath("//div[@data-component-type='s-search-result']"));

for (int i = 0; i < products.size(); i++) {
WebElement product = products.get(i);
System.out.println(products.size());
// Check if the product has a discount
List<WebElement> discountElements = product.findElements(By.xpath("//span[text()='List: ']" + "//span[text()='Typical: ']" + "//span[text()='List Price: ']" + "//span[text()='Typical price: ']" + "//span[text()='New Price: ']"));
if (!discountElements.isEmpty()) {
continue; // Skip products with a discount
}
WebElement productLink = product.findElement(By.tagName("a"));
String productUrl = productLink.getAttribute("href");
// Open the product page
driver.get(productUrl);
// Add the product to the cart
WebElement addToCartButton = driver.findElement(By.id("add-to-cart-button"));
addToCartButton.click();
System.out.println("Added product to the cart");
// Go back to the search results page
driver.navigate().back();
// Re-fetch the product list as the page might have refreshed
products = driver.findElements(By.xpath("//div[@data-component-type='s-search-result']"));
}
// Step 4: Go to cart and check if the products are correct
WebElement cartButton = driver.findElement(By.id("nav-cart"));
cartButton.click();
System.out.println("Opened the cart");
List<WebElement> cartProductPrices = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
boolean productsMatch = true;
for (WebElement cartProductPrice : cartProductPrices) {
String cartPrice = cartProductPrice.getText();
boolean productFound = false;
for (WebElement product : products) {
WebElement priceElement = product.findElement(By.xpath(".//span[contains(@class,'a-price-whole')]"));
String productPrice = priceElement.getText();
if (productPrice.equals(cartPrice)) {
productFound = true;
break;
}
}
if (!productFound) {
productsMatch = false;
break;
}
}
if (productsMatch) {
System.out.println("Products in the cart are correct");
} else {
System.out.println("Products in the cart are incorrect");
}
driver.quit();
}

该计划不会分离没有折扣的产品

最新更新