How to select a cell from a table in selenium when I have unique class name for the table
Below is the dom of the table
<table >
<tbody>
<tr>
<td>data1</td>
<td>data2</td>
</tr>
<tr>
<td>data3</td>
<td>data4</td>
</tr>`your text`
</tbody>
</table>
I tried below code but it is not able to find the table cell
WebElement table = driver.findElement(By.className("unique-class-name"));
for(int i=0; i<expectedTableBodyData.size(); i ){
for(int j=0; j<expectedTableBodyData.get(i).size(); j ){
WebElement tableBodyCell = table.findElement(By.xpath(".//tbody/tr[i 1]/td[j 1]"));
I am not able to find the tableBodyCell
element, I have to use the loop because of some 2D array input data.
I also tried ./tbody/tr[i 1]/td[j 1]
and child::tbody/tr[i 1]/td[j 1]
and descendant::tbody/tr[i 1]/td[j 1]
but it did not work
CodePudding user response:
This should do the job:
table.findElement(By.xpath(String.format("((.//tbody/tr)[%d]/td)[%d]", i 1, j 1)));
The brackets within the xpath to clearly identify which element is being indexed are important.