Taking Web Element Screenshot in Selenium
Taking web element screenshot in selenium will discuss about how to take particular web element screenshot image in selenium webdriver while automating any application. As already we know how to take a screenshot in selenium webdriver. But we do not have provision to take a particular web element screenshot in selenium.
To achieve this, we have to write our own logic to capture the entire screenshot and crop the particular web element on it and save into the particular location. But instead of writing own logic and using the same we can use some third party utility called AShot. It is a WebDriver screenshot utility and by using this we can capture the entire page screenshot and can capture the individual webelement screenshot also.
For this, we need to download the ashot.jar file and add to the project along with the selenium jar files. We can download the ashot.jar file from here.
Below is the sample code to capture the entire page screenshot for any browser:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import ru.yandex.qatools.ashot.AShot; import ru.yandex.qatools.ashot.Screenshot; import javax.imageio.ImageIO; import java.io.File; public class TakeWebElementScreenshot { public static void main(String args[]) throws Exception { System.setProperty("webdriver.gecko.driver", "D:\\Selenium\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("http://demo.automationtesting.in/Register.html"); Thread.sleep(2000); WebElement webElement = driver.findElement(By.cssSelector("#imagetrgt")); Screenshot screenshot = new AShot().takeScreenshot(driver,webElement); ImageIO.write(screenshot.getImage(),"PNG",new File(System.getProperty("user.dir") +"\\ErrorScreenshots\\ElementScreenshot.png")); Thread.sleep(2000); driver.quit(); } }
In the above program 23,24 lines will do the magic. It will capture the entire screen and crop the particular web element as screenshot. For this we need to capture the web element and pass as an argument to the takeScreenshot method. Then this method take care of capturing the entire screenshot and crop the particular web element only from that entire screenshot.
This way we can capture the entire page screenshot using ashot.jar file.
Please watch the youtube video for better understanding.