【发布时间】:2017-05-11 05:10:21
【问题描述】:
我有一个调用 chrome 驱动程序的代码,然后转到 footlocker 的网站。打开 footlocker 的网站后,它会找到并点击 Mens 按钮。然后它会遍历 men 下的产品列表并随机选择一个。我遇到的问题是它每次都选择相同的产品。这是我的代码。选择随机产品的方法在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();
}
}
【问题讨论】:
-
您能提供一个指向footlocker 网站的链接吗?他们似乎对不同的国家有不同的页面布局。同时,您能检查一下 allProducts.size() > 1 吗?
-
确定我使用的网站是针对加拿大的。 footlocker.ca。我将如何进行检查以查看 allProducts.size() 是否>1?我对 Selenium 还很陌生。
标签: java selenium selenium-webdriver selenium-chromedriver selenium-ide