JAVA Selenium Webdriver捕获屏幕截图中的错误区域

时间:2015-04-13 06:28:30

标签: selenium webdriver capture region

我正在使用selenium Web Driver(Java)来自动化我们的Web应用程序。 我需要在所有浏览器中捕获并比较应用程序的每个图标。

首先,我在Firefox中打开了应用程序并使用xpath捕获了图标图像,然后将它们保存在特定路径中。 稍后在另一个浏览器中打开应用程序时比较保存的图像。

为此,我使用以下代码捕获图像,但元素图像未捕获,屏幕中的某些未知区域正在保存。

请帮助,如何获得元素的正确图像。

File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage  fullImg = ImageIO.read(screenshot);
Point point = x.getLocation();
//Get width and height of the element
int eleWidth = x.getSize().getWidth();
int eleHeight = x.getSize().getHeight();
Rectangle rect = new Rectangle(point.getX(),point.getY(),eleWidth, eleHeight);
//Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), rect.width, rect.height);
ImageIO.write(eleScreenshot, "png", screenshot);
//Copy the element screenshot to disk
FileUtils.copyFile(screenshot, new File("E:\\ICONS\\Icon1.jpg"));

1 个答案:

答案 0 :(得分:0)

    driver.switchTo().defaultContent();
    driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='CWinBtn']")));
    WebElement ele =driver.findElement(By.xpath("//*[@id='CCDLinkedformToolbar_cmdPrint']"));
    try{         
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    BufferedImage  fullImg = ImageIO.read(screenshot);
    Point point = ele.getLocation();
    int eleWidth = ele.getSize().getWidth();
    int eleHeight = ele.getSize().getHeight();
    BufferedImage eleScreenshot= fullImg.getSubimage(point.getX()+30, 95, eleWidth, eleHeight);
    ImageIO.write(eleScreenshot, "png", screenshot);
    FileUtils.copyFile(screenshot, new File("E:\\ ICONS\\Icon1.png"));
    }
    catch(Exception e){
         e.printStackTrace();
    }

我对以前的代码所做的更改是,根据我的应用程序分辨率,将值添加到X坐标并将静态值传递给Y坐标。