How to take specific element screenshot in appium

How to Take specific Element screenshot in Appium | Mobile Automation:

Lets us learn how to take screenshot for the specific element, following method i’m using to get screenshot:

public static String elementScreenshot(AppiumDriver driver, MobileElement ele)
{

File screenshotLocation = null;
try{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

BufferedImage fullImg = ImageIO.read(scrFile);
//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”, scrFile);

String path = “screenshots/” + UUID.randomUUID() + “” + “.png”;

screenshotLocation = new File(System.getProperty(“user.dir”) + “/” + path);
FileUtils.copyFile(scrFile, screenshotLocation);

System.out.println(screenshotLocation.toString());

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return screenshotLocation.toString();

}

it will get the element width and height then takes the element screenshot then crop the entire page screenshot to get only element screenshot.

Complete code for taking screenshot of specific element:

package practise;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;

public class TakeElementScreenshot {

AppiumDriver driver;

@BeforeClass
public void setUp() throws MalformedURLException
{
DesiredCapabilities cap=new DesiredCapabilities();
cap.setCapability(“deviceName”, “emulator-5554”);
cap.setCapability(“udid”, “emulator-5554”);
cap.setCapability(“appActivity”, “com.android.calculator2.Calculator”);
cap.setCapability(“appPackage”, “com.android.calculator2”);
cap.setCapability(“platformName”, “Android”);
cap.setCapability(“platformVersion”, “9.0”);
driver=new AppiumDriver(new URL(“http://0.0.0.0:4723/wd/hub”), cap);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}

@Test
public void testExample(){

MobileElement oneBtn=driver.findElement(By.id(“com.android.calculator2:id/digit_1”));
oneBtn.click();
MobileElement plusBtn=driver.findElement(By.id(“com.android.calculator2:id/op_add”));
plusBtn.click();
MobileElement fiveBtn=driver.findElement(By.id(“com.android.calculator2:id/digit_5”));
fiveBtn.click();
MobileElement equalToBtn=driver.findElement(By.id(“com.android.calculator2:id/eq”));
equalToBtn.click();

//passing equalToBtn element to take screenshot
elementScreenshot(driver,equalToBtn);
}

@AfterClass
public void tearDown(){
driver.quit();
}

public static String elementScreenshot(AppiumDriver driver,MobileElement ele)
{

File screenshotLocation = null;
try{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

BufferedImage fullImg = ImageIO.read(scrFile);
//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”, scrFile);

String path = “screenshots/” + UUID.randomUUID() + “” + “.png”;

screenshotLocation = new File(System.getProperty(“user.dir”) + “/” + path);
FileUtils.copyFile(scrFile, screenshotLocation);

System.out.println(screenshotLocation.toString());

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return screenshotLocation.toString();

}

}

Taken Screenshot:

Happy Automation. Cheers !

@Mahantesh_Hadimani it times easier:

File scrFile = element.getScreenshotAs(OutputType.FILE);

@Aleksei i have tried your code in appium. but it is giving below exception:

org.openqa.selenium.UnsupportedCommandException: Method has not yet been implemented.

Could you let me know whether this method supports in appium ? or something im missing ?

complete exception :

org.openqa.selenium.UnsupportedCommandException: Method has not yet been implemented
Build info: version: ‘3.141.59’, revision: ‘e82be7d358’, time: ‘2018-11-14T08:17:03’
System info: host: ‘LP1-AP-51820529’, ip: ‘192.168.137.1’, os.name: ‘Windows 10’, os.arch: ‘amd64’, os.version: ‘10.0’, java.version: ‘1.8.0_221’
Driver info: io.appium.java_client.AppiumDriver
Capabilities {appActivity: com.android.calculator2.Cal…, appPackage: com.android.calculator2, databaseEnabled: false, desired: {appActivity: com.android.calculator2.Cal…, appPackage: com.android.calculator2, deviceName: emulator-5554, platformName: android, platformVersion: 9.0, udid: emulator-5554}, deviceManufacturer: Google, deviceModel: Android SDK built for x86, deviceName: emulator-5554, deviceScreenSize: 1080x1920, deviceUDID: emulator-5554, javascriptEnabled: true, locationContextEnabled: false, networkConnectionEnabled: true, platform: LINUX, platformName: LINUX, platformVersion: 9, takesScreenshot: true, udid: emulator-5554, warnings: {}, webStorageEnabled: false}
Session ID: 4164632d-2331-4514-9cb8-056033deae71
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
at io.appium.java_client.DefaultGenericMobileElement.execute(DefaultGenericMobileElement.java:45)
at io.appium.java_client.MobileElement.execute(MobileElement.java:1)
at io.appium.java_client.android.AndroidElement.execute(AndroidElement.java:1)
at org.openqa.selenium.remote.RemoteWebElement.getScreenshotAs(RemoteWebElement.java:392)
at practise.TakeElementScreenshot.testExample(TakeElementScreenshot.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:822)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1130)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:782)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:113)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:206)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:177)

code i have used:

MobileElement equalToBtn=driver.findElement(By.id(“com.android.calculator2:id/eq”));
equalToBtn.click();
File screenshotLocation = null;
String path = “screenshots/” + UUID.randomUUID() + “” + “.png”;
File scrFile = equalToBtn.getScreenshotAs(OutputType.FILE);
screenshotLocation = new File(System.getProperty(“user.dir”) + “/” + path);
FileUtils.copyFile(scrFile, screenshotLocation);

@Mahantesh_Hadimani hi. zero problem with:

  • Appium: 1.14.0
  • Appium Java-client: 7.1.0
    code tested:
            File srcFile = element.getScreenshotAs(OutputType.FILE);
            File targetFile = new File("myTest.png");
            try {
                FileUtils.copyFile(srcFile, targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            log(targetFile.getAbsolutePath());

-> output got:

/Users/xxxxxx/Documents/Sources/xxxxxxxx/myTest.png

image saved correctly

you probably use an obsolete automation backend

Thanks @Aleksei Let me check with version you have mentioned.