【发布时间】:2016-06-12 14:38:33
【问题描述】:
错误是: 给定的选择器 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();
}
}
【问题讨论】:
-
可以添加表格html吗?
-
谢谢你帮助我。这是 HTML
-
html 太长,无法在此处粘贴,而且我没有看到将其作为文件附加。但是它是来自以下链接的 html:goo.gl/El1PIV
-
我在 firepath 中使用 eval 按钮检查了 xpath,它显示 xpath 有效
标签: java excel selenium webdriver apache-poi