錯誤提示: 給定的選擇器表[class ='stats_table data_grid'] tbody tr [0] td [0]無效或不會導致WebElement 。出現以下錯誤: InvalidSelectorError:無效或非法選擇指定嘗試將webtable導出爲excel時出現無效的選擇器錯誤
觀察: 我已經檢查了cssSelector沒有[ 「+ R +」]和[ 「+ C +」],它是有效的。 所以這個錯誤來自添加[「+ r +」]和[「+ c +」],我無法緩解它。我的總體目標是從mlb.com/stats的webtable中獲取數據,並將其輸入Excel表格中。幾乎99%的代碼工作正常, 除了無效的cssSelector問題。
我的代碼是:
package automate;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MLBtoXL {
static WebDriver driver = new FirefoxDriver();
public static void main(String[] args) throws IOException {
// Navigate to mlb.com/stats
driver.navigate().to("http://goo.gl/El1PIV");
WebElement table = driver.findElement(By.cssSelector
("table[class='stats_table data_grid']"));
List<WebElement> irow = table.findElements(By.tagName("tr"));
int iRowCount = irow.size();
List<WebElement> icol = table.findElements(By.tagName("td"));
int iColCount = icol.size();
FileOutputStream fos = new FileOutputStream
("/Users/HARSHENDU/Desktop/MLBtoXL.xlsx");
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet ws = wb.createSheet("Team Stats");
for(int r=0; r<=iRowCount; r++) {
XSSFRow excelrow = ws.createRow(r);
for(int c=0; c<iColCount; c++) {
// Invalid selector exception coming up for the following cssSelector.
WebElement cellval = driver.findElement
(By.cssSelector("table[class='stats_table data_grid'] tbody tr ["+r+"] td ["+c+"]"));
String cellcontent = cellval.getText();
XSSFCell excelcell = excelrow.createCell(c);
excelcell.setCellType(XSSFCell.CELL_TYPE_STRING);
excelcell.setCellValue(cellcontent);
}
System.out.println("");
}
fos.flush();
wb.write(fos);
fos.close();
end();
}
public static void end() {
driver.close();
driver.quit();
}
}
你可以添加表格html嗎? – Guy
謝謝你幫我的人。這裏是HTML – H1b1
html太長了,無法粘貼到這裏,我也沒有看到將它作爲一個文件附加。但它是從以下鏈接的HTML:http://goo.gl/El1PIV – H1b1