How to Take Element Screenshot in Selenium WebDriver
To take a screenshot of a specific element in Selenium, use the
WebElement method getScreenshotAs(). This captures only the element's image, not the full page, and saves it as a file or byte array.Syntax
Use the getScreenshotAs() method on a WebElement to capture its screenshot. You specify the output type, usually OutputType.FILE to save as a file.
element: The web element you want to capture.getScreenshotAs(OutputType.FILE): Captures the element screenshot as a file.- Save or process the file as needed.
java
File elementScreenshot = element.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(elementScreenshot, new File("element.png"));
Example
This example opens a webpage, finds a button element, takes its screenshot, and saves it as button.png in the project folder.
java
import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class ElementScreenshotExample { public static void main(String[] args) throws IOException { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://www.example.com"); WebElement button = driver.findElement(By.tagName("button")); File screenshot = button.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("button.png")); System.out.println("Element screenshot saved as button.png"); } finally { driver.quit(); } } }
Output
Element screenshot saved as button.png
Common Pitfalls
- Trying to take a screenshot of an element that is not visible or not yet loaded causes errors.
- Using
getScreenshotAs()on theWebDrivercaptures the full page, not the element. - Not handling
IOExceptionwhen saving the file can cause crashes. - For dynamic pages, ensure the element is stable before capturing.
java
/* Wrong: captures full page instead of element */ File fullPage = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); /* Right: captures only the element */ File elementScreenshot = element.getScreenshotAs(OutputType.FILE);
Quick Reference
Remember these key points when taking element screenshots in Selenium:
- Use
WebElement.getScreenshotAs(OutputType.FILE)to capture element only. - Save the file using a utility like Apache Commons
FileUtils.copyFile(). - Ensure the element is visible and loaded before capturing.
- Handle exceptions like
IOException.
Key Takeaways
Use WebElement's getScreenshotAs method to capture only the element's image.
Save the screenshot file properly and handle IO exceptions.
Ensure the element is visible and fully loaded before taking the screenshot.
Avoid using WebDriver's screenshot method when you want only the element image.