尝试将webtable导出为ex​​cel时出现无效的select器错误

错误是:给定的select器表[class ='stats_table data_grid'] tbody tr [0] td [0]无效或不导致WebElement。 发生以下错误:InvalidSelectorError:指定了无效或非法的select器

观察:我检查了没有[“+ r +”]和[“+ c +”]的cssSelector,它是有效的。 所以错误来自于加“[+ r +”]和[“+ c +”],我无法缓解。 我的总体目标是从mlb.com/stats的webtable中获取数据,并将其input到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(); } } 

我相信使用XPath可以解决您的问题:

 WebElement cellval = driver.findElement(By.XPath("//table[@class='stats_table data_grid']/tbody/tr["+r+"]/td["+c+"]")); 

您需要添加index属性。 尝试

 WebElement cellval = driver.findElement(By.cssSelector("table[class='stats_table data_grid'] tbody tr[index="+r+"] td[index="+c+"]");