我有一个包含 12 列的表,其中一列名为“数量”,我需要做的是找出哪一列是数量,然后从表中获取该列的所有数据。
这是我编写的一些粗略代码,但目前它只是给我表中的所有数据,而不是我需要的部分。
// Get the table name
WebElement table = driver.findElement(By.className("compact"));
// Get all the Table headers and look for one the element called quantity.
List<WebElement> allHeaders = table.findElements(By.tagName("th"));
System.out.println("This is the total numbers of headers" + allHeaders.size());
int quantityHead = 0;
// Get the column where the quantity is listed
for(WebElement header : allHeaders)
{
quantityHead++;
if(header.getText().equalsIgnoreCase("Quantity"))
{
System.out.println(header.getText());
System.out.println(quantityHead + " is the column number for the quantity");
}
}
// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
System.out.println("This is how many allRows: " + allRows.size());
// This is how many items are in the order item table. number of rows - 1 coz top row is the headings
int z = allRows.size() - 1;
System.out.println("This is how many items are in the table : " + z );
// Work out the cells we need to get by
// iterate over all the td
for (WebElement row : allRows) {
// now we have all the td
List<WebElement> cells = row.findElements(By.tagName("td"));
for (WebElement cell : cells) {
for(int x=0; x <= allHeaders.size(); x++)
{
int y = x;
// if y = the value where the qty header is then output the text of that cell
if(y == quantityHead )
{
System.out.println();
System.out.println("The quanity is: " + cell.getText());
}
}
}
}