我正在尝试从列表中获取随机元素并单击它。问题是,这些元素是具有属性“数量”的产品,我想单击数量不等于零的随机元素。我正在使用 Selenium 和 Java。
我尝试创建两个列表,一个包含所有元素,另一个包含不等于零的元素,并使用 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;
问题是没有任何东西可以保证产品属性“数量”不等于零。
最佳答案
这是简单的方法。
示例 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:
脚本:
// 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();
关于java - 在Selenium Java中从列表中选择随机元素并单击它,但getAttribute不等于0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570820/