0
我想要使用硒獲取webtable的內容,然後將內容存儲在2d矩陣中。在2d矩陣中存儲webtable的內容
下面是我的代碼:
//Locate the webtable
WebElement reportTable = driver.findElement(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]"));
int rowCount = driver.findElements(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]/tbody/tr")).size(); //Get number of rows
System.out.println("Number of rows : " +rowCount);
String[][] reportMatrix = new String[rowCount-1][]; //Declare new 2d String array
//rowCount-1 because the first row is header which i don't need to store
int mainColCount = 0;
for(int i=2;i<=rowCount;i++) //Start count from second row, and loop till last row
{
int columnCount = driver.findElements(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td")).size(); //Get number of columns
System.out.println("Number of columns : " +columnCount);
mainColCount = columnCount;
for(int j=1;j<=columnCount;j++) //Start count from first column and loop till last column
{
String text = driver.findElement(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td["+j+"]/div")).getText(); //Get cell contents
System.out.println(i + " " + j + " " + text);
reportMatrix[i-2][j-1] = text; //Store cell contents in 2d array, adjust index values accordingly
}
}
//Print contents of 2d matrix
for(int i=0;i<rowCount-1;i++)
{
for(int j=0;j<mainColCount;j++)
{
System.out.print(reportMatrix[i][j] + " ");
}
System.out.println();
}
這給我一個空指針異常在 「reportMatrix [I-2] [J-1] =文本」。
我不明白我在做什麼錯。當我聲明二維數組時,是否必須提供第二個索引?
在此先感謝。
它解決了我的問題。謝謝! – sanaku