java - 使用 selenium 将图像添加到 Excel 工作表的单元格

标签 java selenium selenium-webdriver apache-poi jxl

我正在尝试从网页捕获某个元素的屏幕截图,并希望将捕获的屏幕截图写入 Excel 工作表的单元格。

请找到下面的代码。我无法决定为 Label 的第三个参数传递什么内容

WebDriver driver;
String baseUrl = "http://www.google.com";

@Test
public void test() throws IOException, BiffException, RowsExceededException, WriteException {
    WebElement ele = driver.findElement(By.id("hplogo"));

    // Get entire page screenshot
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    BufferedImage fullImg = ImageIO.read(screenshot);

    // Get the location of element on the page
    Point point = ele.getLocation();

    // Get width and height of the element
    int eleWidth = ele.getSize().getWidth();
    int eleHeight = ele.getSize().getHeight();

    // Crop the entire page screenshot to get only element screenshot
    BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
    ImageIO.write(eleScreenshot, "png", screenshot);

    // Copy the element screenshot to disk
    File screenshotLocation = new File("D:\\GoogleLogo_screenshot.png");
    FileUtils.copyFile(screenshot, screenshotLocation);

    String excelPath = "D:\\" +  appName + ".xls";
    File file = new File(excelPath);
    WritableWorkbook wbook = Workbook.createWorkbook(file);
    WritableSheet wsheet = wbook.createSheet("Seeds", 0);

    **Label lab = new Label(0, 0, );**

    wsheet.addCell(lab);
    wbook.write();
    wbook.close();

}

}

最佳答案

您应该使用以下方法:

    // **Label lab = new Label(0, 0, );**
    // wsheet.addCell(lab);

    WritableImage image = new WritableImage(0, 0, 4, 6, screenshotLocation);
    wsheet.addImage(image);

    // Parameters:
    // x - the column number at which to position the image
    // y - the row number at which to position the image
    // width - the number of columns cells which the image spans
    // height - the number of rows which the image spans
    // image - the source image file

您应该将这两个参数“4、6”替换为实际大小。

关于java - 使用 selenium 将图像添加到 Excel 工作表的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39593180/

相关文章:

java - Selenium WebDriver 无法找到页面源中不存在但通过开发人员工具查看时存在于 HTML 中的元素

javascript - 如何通过文本 [protractor] 在 ng-table 中查找特定行

selenium - 测试按钮同时在浏览器的不同选项卡中单击

java - 使用 Spring Boot 通过 jndi 查找配置两个数据源

java - Android ExpandableListView 不展开/不可点击

java - 如何在 Selenium IDE 目标中使用正则表达式?

javascript - 用于识别复选框的正确 xpath

java - 使用 WebDriver 查找元素时出现 ElementNotInteractableException 异常

java - 如何在Android Java中使用Kotlin lib之前实现回调(Kotlin)

java - 如何在 Maven 项目中正确导入 org.w3c.dom?