I am trying to capture screenshot of a specific element on Android 4.4 using Appium + Selenium. I can successfully capture the screenshot of the whole screen, but when I try to capture screenshot on a specific element on the page, it always capture the wrong position of the element. See the screenshot below:
First I capture whole screen, and the full screenshot captured successfully. And then I try to capture the element inside the red rectangle, here is what i get, instead of capturing the “Fit: As Expected” element, it captures a blank top left area:
Here is the code I used to capture screenshot:
public void takeScreenshot() throws Exception {
driver.get("http://www.amazon.com/gp/aw/d/B0018OOVPC");
//Find the element
WebElement element=driver.findElement(By.id("fitRecommendationsLink"));
//Cycle with red rectangle
((JavascriptExecutor) driver).executeScript("arguments[0].style.border='3px solid red'", element);
//Take screenshot on full screen
File screenshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage img = ImageIO.read(screenshot);
ImageIO.write(img, "png", screenshot);
FileUtils.copyFile(screenshot, new File(TestSuiteUtils.getSnapShotsBaseFolder("Test") + "/FullScreenshot.png"));
//Take screenshot of the element only
int height = element.getSize().height;
int width = element.getSize().width;
Rectangle rect = new Rectangle(width,height);
Point p = element.getLocation();
logger.info("Element position: X=" + p.getX() + " Y=" + p.getY());
logger.info("Element width=" + rect.width + " height=" + rect.height);
BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height);
ImageIO.write(dest, "png", screenshot);
FileUtils.copyFile(screenshot, new File(TestSuiteUtils.getSnapShotsBaseFolder("Test") + "/PartialScreenshot.png"));
}
The driver is an instance of ScreenshotAppiumDriver which extends AppiumDriver and implements TakesScreenshot interface. The code to configure the driver:
public static void getMobileChromeOnAndroidDevice() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "Android");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");
capabilities.setCapability(CapabilityType.VERSION, "4.4");
String endpoint = EnvironmentUtil.getInstance().getEndpoint();
try {
driver = new ScreenShotAppiumDriver(new URL(endpoint), capabilities);
} catch (Exception e) {
e.printStackTrace();
}
}
Has anyone encountered this before? Any ideas?