简体   繁体   中英

Selenium Webdriver Java: How to click on a particular cell in table using row and column numbers

I have written a code to verify if a given text is present in that row or not but how do i click in a particular cell? Please help me.
Below is the code i have written for verifying the text.

package com.Tables;

import java.util.List;

public class HandlingTables {

public static void main(String[] args) throws InterruptedException {
    String s="";
    System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.w3schools.com/html/html_tables.asp");
    WebElement table = driver.findElement(By.className("w3-table-all"));
    List<WebElement> allrows = table.findElements(By.tagName("tr"));
    List<WebElement> allcols = table.findElements(By.tagName("td"));
    System.out.println("Number of rows in the table "+allrows.size());
    System.out.println("Number of columns in the table "+allcols.size());

    for(WebElement row: allrows){
        List<WebElement> Cells = row.findElements(By.tagName("td"));
        for(WebElement Cell:Cells){
            s = s.concat(Cell.getText());   
        }
    }
    System.out.println(s);
    if(s.contains("Jackson")){
        System.out.println("Jackson is present in the table");
    }else{
        System.out.println("Jackson is not available in the table");
    }
    Thread.sleep(10000);
    driver.quit();
  }
}  

You could modify your loop to click, instead of contat'ing a giant string

for(WebElement row: allrows){
    List<WebElement> Cells = row.findElements(By.tagName("td"));
    for(WebElement Cell:Cells){
        if (Cell.getText().contains("Jackson"))
            Cell.click();
    }
}

Keep in mind though, that clicking the <td> may not actually trigger as the <td> may not be listening for the click event. If it has a link in the TD, then you can do something like:

Cell.findElement("a").click();

You will have to build a dynamic selector to achieve this.

For example:

private String rowRootSelector = "tr";
private String specificCellRoot = rowRootSelector + ":nth-of-type(%d) > td:nth-of-type(%d)";

And in the method where you take Row and Column as input parameter, the selector has to be built.

String selector = String.format(specificCellRoot, rowIndex, columnIndex);

And, now you can click or do any other operation on that web element.

driver.findElement(By.cssSelector(selector));

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