Mike
Mike

Reputation: 919

Is there a better to way to write this code in Java(for web table handling)?

I have two methods which does the same. Unfortunately, Option Two works some times (5 out of 10 times)... Option One works rarely (2 out of 10 times)... Is there a better to way to write this code...

One:

public static void clickOnLinkinWebTable(WebElement webTable, String lookUpValue) throws MyException {
    for (WebElement row : webTable.findElements(By.xpath("tr"))) {
        for (WebElement col : row.findElements(By.xpath("td")))
            if (col.getText().equals(lookUpValue)) {
                col.findElement(By.partialLinkText(lookUpValue)).click();
                return;
            }

    }
}

Two:

public static void clickOnLinkinWebTable(String tableXpathRow, String lookUpValue) throws MyException {
    int row_cnt = driver.findElements(By.xpath(tableXpathRow)).size();
        for (int row_num = 1; row_num <= row_cnt; row_num++) {
                int col_cnt = driver.findElements(By.xpath(tableXpathRow+"["+row_num+"]"+"/td")).size();
                for (int col_num = 1; col_num <= col_cnt; col_num++) {
                String cellValue = driver.findElement(By.xpath(tableXpathRow+"["+row_num+"]/td["+col_num+"]")).getText();
                if(lookUpValue.equalsIgnoreCase(cellValue)){
                    WebElement elementLink = driver.findElement(By.xpath(tableXpathRow+"["+row_num+"]/td["+col_num+ "]/a"));
                elementLink.click();
                return;
            }
        }
    }
}

Works some times / rarely: I am running tests in a test suite. This method is called atleast 15 times in the test suite (in the same page). Works some times but does n't work sometime when this method is called.

Upvotes: 1

Views: 331

Answers (1)

Suchitra R.D
Suchitra R.D

Reputation: 200

Can use xpath of the lookup for clicking on the webtable link.

driver.findElement(By.xpath(path)).click();

where

path="//td[contains(text(),lookupvalue)]"

(this can be done by string concat like below)

String s="//td[contains(text(), ";
String qt=")]";
String path=(s.concat(lookupvalue)).concat(qt);

Hope this helps.

Upvotes: 2

Related Questions