我有一個代碼調用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相當陌生。 –