[英]Select a random element from a list in Selenium Webdriver Java
[英]Select random element from the list in Selenium Java and click on it, but getAttribute is not equal to zero
我正在嘗試從列表中獲取隨機元素,然后單擊它。 事實是,元素是具有“數量”屬性的產品,我想單擊數量不等於零的隨機元素。 我正在使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.