Home > Enterprise >  Finding all cells within the table instead of cells within current row in foreach loop in Java
Finding all cells within the table instead of cells within current row in foreach loop in Java

Time:11-17

My code is like below.

    private List<WebElement> reports;
    public List<WebElement> getReports(){
        return Common.returnElementList(DriverFactory.getDriver(), reportsMenu, reports);
    }
    public Map<String, String> getReportDesc() {
        Map<String, String> temp = new HashMap<>();
        for(WebElement item: getReports()){
            List<WebElement> cols = item.findElements(By.xpath("/child::td[@role='gridcell']"));
            String key = Common.getElementText(DriverFactory.getDriver(), cols.get(0));
            String desc = Common.getElementText(DriverFactory.getDriver(), cols.get(1));
            temp.put(key, desc);
        }
        return temp;
    }

With item.findElements(By.xpath("/child::td[@role='gridcell']")); I am trying to get the cells of that specific row, instead I am getting all the cells in that table.

How Can I get the specific row columns?

CodePudding user response:

You need to use relative XPath locator.
Since you didn't share a link to the page containing that table we can only guess. So, I guess:
Instead of

item.findElements(By.xpath("/child::td[@role='gridcell']"));

try this:

item.findElements(By.xpath(".//td[@role='gridcell']"));

The dot . infront of the XPath means this is relative XPath, we want to locate element matching //td[@role='gridcell'] inside current node item.
Otherwise driver will search for all elements matching /child::td[@role='gridcell'] expression form the first, top element on the page.

  • Related