我有一个代码调用chrome驱动程序,然后进入footlocker的网站。打开Footlocker的网站后,它找到并点击男士按钮。然后它通过男性下的产品清单并随机选择一个。我遇到的问题是每次都选择相同的产品。这是我的代码。选择一个随机的产品的方法是在selectRandomProduct从Selenium Webdriver的列表中选择一个随机元素Java
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();
}
}
你能提供一个链接到footlocker网站吗?他们似乎对不同的国家有不同的页面布局。与此同时,你可以检查是否allProducts.size()> 1吗? – oschlueter
确定我使用的网站是加拿大。 http://www.footlocker.ca/。我将如何执行检查以查看allProducts.size()是否大于1?我对Selenium相当陌生。 –