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

问题描述 投票:0回答:3

我被 Amazon.com 的自动化困住了

自动化步骤:

  1. 打开 www.amazon.com 网站。
  2. 在搜索框中输入文本“Headphones”。按回车键
  3. 从第一页显示的结果中,将所有标记为“Best seller”的商品添加到购物车。

代码我试过:

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 种畅销产品添加到购物车。 任何帮助将不胜感激。

java selenium selenium-webdriver xpath
3个回答
1
投票

在下面的代码中, 用于获取所有没有赞助(重复)的畅销商品。使用流从畅销书元素中获取 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']"))
    ));
});

1
投票

看来你错了 placement increase count

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();

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


0
投票

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

  1. 去亚马逊
  2. 按词搜索笔记本电脑
  3. 添加第一页的所有结果,不含打折产品
  4. 去购物车检查产品是否正确

这是代码:

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();
}

程序不区分没有折扣的产品

© www.soinside.com 2019 - 2024. All rights reserved.