尝试将webtable导出为Excel时,选择器错误无效

时间:2016-02-29 14:01:49

标签: java excel selenium webdriver apache-poi

错误是: 给定的选择器表[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();
    }

}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您需要添加index属性。尝试

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