'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.



Solution 1:[1]

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:

enter image description here

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();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 supputuri