How to Capture WebElement Screenshot in Selenium Webdriver using selenium 4
In this blog, we will learn how to capture webelement screenshot using selenium. Till Selenium 3 we have an option that to take the screenshot for an entire webpage. From selenium 4 onwards they have introduced an option that to capture a webelement. Previously, using some third party libraries like Ashot, shutterbug to capture the webelemet or webpage.
Pre-requisites:
- Add the selenium-4-alpha.jar file in your project or add the corresponding dependency is yours is a Maven project
- in your class file, inspect the target element and store it in a webelement.
- Now, use the regular screenshot logic method and store the value in a folder using Filehandler method.
- Instead of driver, use the webelement reference variable to capture the screenshot of the target element instead of full webpage.
package Basics; import java.io.File; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.io.FileHandler; public class CaptureWebelementScreenshot { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub WebDriver driver; System.setProperty("webdriver.chrome.driver", "E:\\Selenium-Softwares\\chromedriver.exe"); //System.setProperty("webdriver.gecko.driver", "E:\\Selenium-Softwares\\geckodriver.exe"); driver=new ChromeDriver(); driver.get("http://demo.automationtesting.in/Register.html"); Thread.sleep(3000); WebElement element = driver.findElement(By.id("imagetrgt")); File source = ((TakesScreenshot)element).getScreenshotAs(OutputType.FILE); FileHandler.copy(source, new File("./screenshots/element.png")); Thread.sleep(3000); driver.quit(); } }
Please watch the Youtube video for better understanding.