【问题标题】:Screenshot specific element with Selenium使用 Selenium 截图特定元素
【发布时间】:2016-06-20 15:23:20
【问题描述】:

注意:我知道这个问题之前已经被问过几次,但是我遇到了其他人似乎没有遇到的问题。

即使我似乎正确地获取了元素的点及其宽度和高度,但最终的裁剪是不正确的。就像我截取的屏幕截图与网页的尺寸不同。我正在使用 Chrome 驱动程序。

这是我尝试获取 google 徽标图像的屏幕截图的代码:

WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
WebElement ele = driver.findElement(By.id("hplogo"));
//Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = null;
try {
    fullImg = ImageIO.read(screenshot);
} catch (IOException e) {

}
//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);
try {
    ImageIO.write(eleScreenshot, "png", screenshot);
} catch (IOException e) {

}
//Copy the element screenshot to disk
File screenshotLocation = new File("/Users/M/Desktop/stuff/logo.png");
try{
    FileUtils.copyFile(screenshot, screenshotLocation);
}catch(IOException e){

}

这是我的最终徽标图片:

这是它应该得到的(就像 png 而不是 gif):

有人知道会发生什么吗?

【问题讨论】:

  • 你确定你得到了错误的图像。因为对我来说代码完美运行
  • 是的,我在问题中发布了图片。我也尝试了几种不同的元素。这真的让我很困惑。您使用的是 Chrome 驱动程序吗?您使用的是什么版本的 Selenium? @Madhan
  • 它看起来是正确的宽度和高度,但它就像放大或屏幕截图上的东西?就好像截图的点和宽高和网页不一样。
  • 使用 Windows 7、Java 1.7.101、Selenium 2.53、ChromeDriver 2.21、Chrome 51

标签: java selenium screenshot selenium-chromedriver


【解决方案1】:

检查您的操作系统是否有自定义缩放。我在 Windows 上使用 125% 缩放时遇到了同样的问题。

【讨论】:

    【解决方案2】:

    请参阅下面的屏幕截图了解更多详细信息。

    转到您的系统设置 > 搜索显示 > 将“Make Everything Bigger”下拉菜单的值更改为 100%。然后再次运行代码,这对你来说很好。

    【讨论】:

      猜你喜欢
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多