簡體   English   中英

從Selenium Webdriver Java中的列表中選擇一個隨機元素

[英]Select a random element from a list in Selenium Webdriver Java

我有一個代碼,該代碼調用chrome驅動程序,然后轉到Footlocker的網站。 打開footlocker的網站后,它會找到並單擊“男士”按鈕。 然后,它會瀏覽男性下的產品列表,並隨機選擇一個。 我遇到的問題是它每次都會選擇相同的產品。 這是我的代碼。 選擇隨機產品的方法在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();
}

}

我瀏覽了該網站,發現您的xpath( //*[@id='endecaResultsWrapper']/div[3] )選擇了包含所有圖像的整個div。 因此,基本上,當您單擊隨機元素時,它只會找到一個(主div)。 如果要單擊60種產品之一,則應嘗試類似以下操作: //*[@id='endecaResultsWrapper']/div[3]//img

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM