如何迭代通过表来查找所有值

时间:2015-07-13 22:57:51

标签: java selenium

我试图提取并打印与@ class ='Grp'属性相关的所有值。根据HTML,此属性在表中出现两次。使用我的代码,我可以找到并打印Text 1值,但我无法获得Text 2值。我认为循环是问题所在,但不确定如何修复。

WebElement table = driver.findElement(By.id("Table"));
WebElement tbody = table.findElement(By.tagName("tbody"));
WebElement tr = tbody.findElement(By.tagName("tr"));
List<WebElement> rows = tr.findElements(By.tagName("td"));
logger.info("number of rows: " +rows.size());
ArrayList<String> list = new ArrayList<>();

for (int i=0; i<rows.size();i++)    
    {
        WebElement heading = table.findElement(By.xpath("//*[@class='Grp']"));
        if (heading.getText().trim().contains("Text"))
            { 
                logger.info("text: " +heading.getText().trim());
                list.add(heading.getText().trim());
            }

HTML

<table id="Table" width="100%" cellspacing="0" cellpadding="0" border="0">
<thead class="Head">
<tbody>
<tr style="height:30px">
<td class="Grp" style="background-color:#686890;white-space:nowrap" colspan="99">Text 1</td>
</tr>
</tbody>
<tbody>
<tr style="height:30px">
<td class="Grp" style="background-color:#686890;white-space:nowrap" colspan="99">Text 2</td>
</tr>
</tbody>

1 个答案:

答案 0 :(得分:0)

你可以这样做:

List<WebElement> rows = driver.findElements(By.className("Grp"));
logger.info("number of rows: " +rows.size());
ArrayList<String> list = new ArrayList<>();

for (WebElement row : rows)    
{
        if (row.getText().trim().contains("Text"))
            { 
                logger.info("text: " + row.getText().trim());
                list.add(row.getText().trim());
            }
}