Dustin N. Dustin N. - 1 year ago 67
Java Question

Dynamically Generate CSS Selector From Table Value

We have a website that is built upon a ton of tables. Each cell within the rows is clickable. I am working on a way to dynamically build the cssSelector info by providing the table name and value I want to click on. I am getting close (I think).

Using the practice table at ToolsQA, say I want to build the cssSelector for the value "Taiwan".

It's cssSelector is:

.tsc_table_s13 > tbody:nth-child(4) > tr:nth-child(3) > td:nth-child(2)

I am iterating through the table and have successfully been able to enter the cell using the value ("Taiwan") I specified, however, I'm not sure how to get the value of the row and column it is currently on.

Here is the code I am using so far:


String table = ".tsc_table_s13 > tbody:nth-child(4)";
String cellValue = "Taiwan";

getCell(table, cellValue);

// Get the cell of a particular value
public static void getCell(String table, String value) throws IOException{

// Grab the table
WebElement tableName = driver.findElement(By.cssSelector(table));

// Now get all the TR elements from the table
List<WebElement> allRows = tableName.findElements(By.tagName("tr"));

// And iterate over them, getting the cells
for (WebElement row : allRows) {
List<WebElement> cells = row.findElements(By.tagName("td"));

// Print the contents of each cell
for (WebElement cell : cells) {
// System.out.println(cell.getText());
if (cell.getText().equals(value))
String cellValue = table + " > tr:nth-child(" + row. + ") > td:nth-child(" + cell + ")";

} // end if text equals

} // end for loop for cells
} // end for loop for all rows

} // end getCell function

Answer Source

So here's a quick example of how you can use XPath to find text in a table and get a reference to the element. You provide the text to search for and it gets inserted into an XPath. That XPath below, searches for a TD that contains that text. This is just a simple case. If you have a lot of repetitive text in your table, you'll have to post some examples so that I can update the code to take that into account.

String searchText = "China";
WebElement e = driver.findElement(By.xpath("//td[text()='" + searchText + "']"));
System.out.println(e.getText()); // you can get the text in the cell
System.out.println(e.getAttribute("outerHTML")); // you can get the HTML of the TD
e.click(); // you can click the element also but in this case it won't do anything since it's just a TD with text