从Selenium Webdriver Java中的列表中选择一个随机元素

时间:2016-12-26 21:05:59

标签: java selenium selenium-webdriver selenium-chromedriver selenium-ide

我有一个调用chrome驱动程序的代码然后转到footlocker的网站。打开footlocker的网站后,它会找到并点击Mens按钮。然后它会查看男性产品列表并随机选择一个。我遇到的问题是它每次都选择相同的产品。这是我的代码。选择随机产品的方法在selectRandomProduct

public class FootlockerExample {

WebElement next;
WebDriver driver = new ChromeDriver();

public void productOne (){

    // Open Chrome Browser
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Working\\Workspace\\SeleniumProject\\chromedriver.exe");

    // Open Footlocker website and maximize window
    driver.get("http://www.footlocker.ca/");
    driver.manage().window().maximize();

    // Find button element 'Mens' and click
    next = driver.findElement(By.xpath("//*[@id='global-nav']/ul/li[1]/a"));
    next.click();

    // Select a random product
    selectRandomProduct();

    // Print out the product name and price
    String productName = driver.findElement(By.xpath("//*[@id='product_form']/div/span[2]/div/div[1]")).getText();
    String Price = driver.findElement(By.xpath("//*[@id='product_form']/div/span[2]/div/div[2]")).getText(); 
    System.out.println("The 1st random product is " + productName + " and it's cost is " + Price + ".");

    // Execute new method
    productTwo();
}

public void productTwo(){

    // Go back a browser page
    driver.navigate().back();
    selectRandomProduct();

    // Print out the product name and price
    String productName = driver.findElement(By.xpath("//*[@id='product_form']/div/span[2]/div/div[1]")).getText();
    String Price = driver.findElement(By.xpath("//*[@id='product_form']/div/span[2]/div/div[2]")).getText(); 
    System.out.println("The 2nd random product is " + productName + " and it's cost is " + Price + ".");
}

public void selectRandomProduct(){

    // Find and click on a random product
    List<WebElement> allProducts = driver.findElements(By.xpath("//*[@id='endecaResultsWrapper']/div[3]"));
    Random rand = new Random();
    int randomProduct = rand.nextInt(allProducts.size());
    allProducts.get(randomProduct).click();
}

public static void main(String[] args) {

    FootlockerExample obj1 = new FootlockerExample();
    obj1.productOne();
}

}

1 个答案:

答案 0 :(得分:1)

我查看了网站,发现你的xpath(//*[@id='endecaResultsWrapper']/div[3])选择了所有图像的整个div。所以基本上,当你点击一个随机元素时,它只找到一个(主div)。如果您想点击60种产品中的一种,您应该尝试这样的事情://*[@id='endecaResultsWrapper']/div[3]//img