简体   繁体   中英

How to iterate thru table to find all values

I am attempting to extract and print all values associated with @class='Grp' attribute. According to HTML, this attribute appears twice within table. Using my code, I can find and print Text 1 value, but I cannot get Text 2 value. I think for loop is the problem, but not sure how to fix.

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>

You could do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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