plata :
Tratando de conseguir todas las td
(células) bajo una específica th
(cabecera)
HTML:
<table width="800">
<tbody>
<tr>
<th><b>User ID</b></th>
<th><b>Workforce ID</b></th>
<th><b>Given Name</b></th>
<th><b>Surname</b></th>
<th><b>Division</b></th>
<th><b>Hire Date</b></th>
<th><b>Department</b></th>
<th><b>emplType</b></th>
<th><b>Associations</b></th>
<th><b>SAP Roles</b></th>
<th><b>Community</b></th>
<th><b>Active</b></th>
</tr>
<tr>
<td class="active"><a href="?username=utest001">utest001</a></td>
<td class="active">00700001</td>
<td class="active">User</td>
<td class="active">Test001</td>
<td class="active">Coles</td>
<td class="active">2015-10-27</td>
<td class="active">CHFITVB</td>
<td class="active">S</td>
<td class="active">IAM</td>
<td class="active"></td>
<td class="active">Workforce</td>
<td class="active">Y</td>
</tr>
<tr>
<td class="disabled"><a href="?username=utest002">utest002</a></td>
<td class="disabled">00700002</td>
<td class="disabled">Vasia</td>
<td class="disabled">Smith</td>
<td class="disabled">Coles</td>
<td class="disabled">2015-11-16</td>
<td class="disabled">C0584SV</td>
<td class="disabled">W</td>
<td class="disabled"></td>
<td class="disabled"></td>
<td class="disabled">Workforce</td>
<td class="disabled">N</td>
</tr>
</tbody>
</table>
Método:
public List<WebElement> getCellsUnderHeader(WebElement table, String headerName) {
List<WebElement> thList = table.findElements(By.cssSelector("th > b"));
List<String> headers = new ArrayList<>();
thList.stream().forEach(th -> headers.add(th.getText()));
int index = headers.indexOf(headerName);
List<WebElement> trList = table.findElements(By.tagName("tr"));
List<WebElement> tdList = new ArrayList<>();
List<WebElement> columnCells = new ArrayList<>();
WebElement cell = null;
for (WebElement tr : trList) {
tdList = tr.findElements(By.tagName("td"));
cell = tdList.get(index); // Getting out of bounds here
columnCells.add(cell);
}
return columnCells;
}
Resultado actual:
java.lang.IndexOutOfBoundsException: Índice 0 fuera de límites para la longitud 0
Resultado Esperado:
Devuelve una List<WebElement>
que contiene 2 td
(con a
etiqueta) bajo encabezado User ID
.
Chico :
trList
contiene el <tr>
con las cabeceras, que no tienen <td>
etiquetas por lo que en la primera for
iteración tdList
está vacío y tdList.get(index)
lanza IndexOutOfBoundsException
.
Se puede recorrer por el índice de cambio
for (int i = 1 ; i < trList.size() ; i++) {
tdList = trList.get(i).findElements(By.tagName("td"));
cell = tdList.get(index);
columnCells.add(cell);
}
O enviar primer elemento
for (WebElement tr : trList.subList(1, trList.size())) {
tdList = tr.findElements(By.tagName("td"));
cell = tdList.get(index);
columnCells.add(cell);
}