简体   繁体   中英

Select random element from the list in Selenium Java and click on it, but getAttribute is not equal to zero

I'm trying to get random element from the list and click on it. The thing is, the elements are products which have attribute "quantity" and I want to click on the random element which quantity is not equal to zero. I'm using Selenium and Java.

I tried to create two lists, one with all elements and the other to put elements which are not equals to zero and with Random class to click on element but to no avail, it does click on random element but sometimes hits the one with zero quantity.

    List<WebElement> products= driver.findElements(By.id("elementId"));
    List<Integer> productsNotEqualToZero = new ArrayList<>();

    for(webElement:products){
    if(!webElement.getAttribute("quantity").equals("0")){


productsNotEqualToZero.add(Integer.ParseInt(webElement.getAttribute("quantity 
    ")))
    }
    }
    Random random = new Random();
    int result = random.nextInt(productsNotEqualToZero.size());
    products.get(result).click;

The problem is that nothing guarantees that product attribute "quantity" is not equals to zero, I'd really appreciate help on this, thank you. First time posting so I'm sorry if I haven't formatted code properly.

Here is the simple approach.

Sample HTML:

 <html><head></head><body><div> <select> <option quantity="1">Apple</option> <option quantity="4">Banana</option> <option quantity="0">Cherry</option> <option quantity="1">DragonFruit</option> </select> </div><table border="1" id="mytable"> </table></body></html> 

Xpath:

在此处输入图片说明

Script:

// get all products whose quanity >0
    List<WebElement> productElems = driver.findElements(By.xpath("//select/option[@quantity>'0']"));
    // get the len of productElems
    int maxProducts = productElems.size();
    // get random number
    Random random = new Random();
    int randomProduct = random.nextInt(maxProducts);
    // Select the list item
    productElems.get(randomProduct).click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM