简体   繁体   中英

How to automate click link in table cell by column name and row index using selenium (JAVA)

I want a generic approach to perform click link in table cell by providing column name and row index .

There may be multiple type of HTML table structure, but I need generic function which perform action in every table which looks like a generic HTML table.

For eg. following some generic tables are define :-

1- first table structure

 <table>
 <tr>
 <th>column1</th><th>column2</th><th>column3</th>
 </tr>
 <tr>
 <td><a href="">Link1</a></td><td><a href="">Link2</a></td><td><a href="">Link2</a></td>
 </tr>
 </table>

2- second table structure

 <table>
 <tr>
 <td>column1</td><th>column2</th><td>column3</td>
 </tr>
 <tr>
 <td><a href="">Link1</a></td><th><a href="">Link2</a></th><td><a href="">Link2</a></td>
 </tr>
 </table>

3- third table structure

 <table>
 <tr>
 <td>column1</td><td>column2</td><td>column3</td>
 </tr>
 <tr>
 <td><a href="">Link1</a></td><td><a href="">Link2</a></td><td><a href="">Link2</a></td>
 </tr>
 </table>

Here If I provide two parameter for eg.

String columnName = "column2", int rowIndex = 1;

then My generic function perform click link Link2 in table cell at 2,1 in all tables.

I can find the table using WebDriver as follows :-

 WebDriverWait wait = new WebDriverWait(driver, 10000);
 WebElement tableElment = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table")));

But I do not know how to make a generic function to process this table as I want.

Please help me to create a generic function in Java to achieve this task.

Using JavascriptExecutor in WebDriver is also acceptable..

Pseudo code or Algorithm to achieve this is also acceptable..

Thanks in advance...:)

You could get the index of the column matching the targeted header and then return the link in the targeted row/column. I would use a piece of JavaScript for this task:

static WebElement getTableLink(WebElement table, String column, int row) {
    JavascriptExecutor js = (JavascriptExecutor)((RemoteWebElement)table).getWrappedDriver();

    WebElement link = (WebElement)js.executeScript(
        "var rows = arguments[0].rows, header = arguments[1], iRow = arguments[2];      " +
        "var iCol = [].findIndex.call(rows[0].cells, (td) => td.textContent == header); " +
        "return rows[iRow].cells[iCol].querySelector('a');                              " ,
        table, column, row);

    return link;
}

Usage:

// get the table
WebElement tableElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("table")));

// click the link in column "column2", row 1
getTableLink(tableElement, "column2", 1).click();

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