错误是: 给定的选择器 table[class='stats_table data_grid'] tbody tr [0] td [0] 无效或不会生成 WebElement。发生以下错误: InvalidSelectorError:指定了无效或非法的选择器
观察: 我已经检查了没有 ["+r+"] 和 ["+c+"] 的 cssSelector 并且它是有效的。 所以错误来自添加 ["+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();
}
}
最佳答案
我相信使用 XPath 可以解决您的问题:
WebElement cellval = driver.findElement(By.XPath("//table[@class='stats_table data_grid']/tbody/tr["+r+"]/td["+c+"]"));
关于java - 尝试将 webtable 导出到 Excel 时出现无效选择器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35701550/