使用java webdriver存储,搜索和处理动态webtable行

时间:2017-06-16 22:18:09

标签: selenium selenium-webdriver collections enums hashmap

有几个解决方案,但没有hashmap和enum。

网站表格元素简单tbody,tr,td。下面的代码,我在行列表中有多个元素,或者行数据作为另一个列表中的字符串。

List<WebElement> rows = table.findElements(By.tagName("tr"));
        List<ArrayList<String>> rowsData = new ArrayList<ArrayList<String>>();

        for(WebElement row:rows){
            List<WebElement> rowElements = row.findElements(By.tagName("td"));

            ArrayList<String> rowData = new ArrayList<String>();

            for(WebElement column:rowElements){
                rowData.add(column.getText().toString());
            }

            rowsData.add(rowData);
        }

一行可以是: 12,ab,apple,red,-1000; 66,ac,grape,blue,1000;等

我必须检查所有行并找到第一行为红色,苹果且最后一行不大于0并单击。

更有用的选项可以是枚举和hashmap。 Hashmap键可以是枚举值,如ID,NAME,FRUIT,COLOR,NUMBER。检查hashmap有COLOR = red,name = apple等。

任何解决方案?我认为它对每个人都非常有用!

提前致谢!

1 个答案:

答案 0 :(得分:0)

您是否考虑过将行创建为对象?像这样的东西

public class Fruit {
   private String name;
   private int id;
   //go horizontally with your column names;
   //have getters/setters here
}

现在你的代码可能会略有不同,如

List<WebElement> rows = table.findElements(By.tagName("tr"));
List<Fruit> fruits = new ArrayList<Fruit>();

for(WebElement row:rows){
     List<WebElement> rowElements = row.findElements(By.tagName("td"));
     Fruit fruit = new Fruit();
     //you know first column is name or so on
     //or store column header order and use it here
     fruit.setName(rowElements.get(0).getText()); 
     fruit.id(rowElements.get(1).getText());
     fruits.add(fruit);
}

现在您可以迭代fruits