我被困在Amazon.com的自动化中

自动化步骤:


打开www.amazon.com网站。
在搜索框中输入文字“耳机”。点击进入
从第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用来获取所有没有赞助(重复)的畅销商品。使用来自畅销书元素的流get 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']"))
    ));
});

10-06 08:06