简体   繁体   English

从Selenium Java中的列表中选择随机元素,然后单击它,但getAttribute不等于零

[英]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. 我正在使用Selenium和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. 我试图创建两个列表,一个包含所有元素,另一个放置不等于零的元素,并使用Random类单击元素,但无济于事,它确实单击了随机元素,但有时命中的数量为零。

    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示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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