How to Take WebElement Screenshot in Selenium 4 (Java)
By Bhau Automation Lab • Selenium 4 WebElement Screenshot Tutorial
🎯 What You Will Learn
- How to take screenshot of specific WebElement in Selenium
- How to capture full page screenshot in Selenium 4
- Using TakesScreenshot interface
- Using getScreenshotAs() method
- How to capture screenshot on test failure
- Real-time automation framework usage
💡 In automation frameworks, capturing WebElement screenshots helps debug UI failures quickly.
📌 Taking Screenshot of Specific WebElement
In Selenium 4, we can directly capture a screenshot of a specific WebElement using getScreenshotAs() method.
WebElement logo = driver.findElement(By.id("logo"));
File source = logo.getScreenshotAs(OutputType.FILE);
File destination = new File("./Screenshots/logo.png");
FileUtils.copyFile(source, destination);
System.out.println("WebElement screenshot captured successfully!");
📌 Taking Full Page Screenshot
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./Screenshots/fullpage.png"));
📍 Using Timestamp in Screenshot Name
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File destination = new File("./Screenshots/Element_" + timestamp + ".png");
⚡ Screenshot on Test Failure (Framework Use Case)
- Inside @AfterMethod (TestNG)
- Using ITestListener interface
- Inside catch block
❓ Common Interview Questions
Q: Can we take screenshot of specific element in Selenium 4?
A: Yes, using WebElement.getScreenshotAs().
Q: Which interface is used to capture screenshots?
A: TakesScreenshot interface.
🎥 Watch Complete Video Tutorial
👉 Watch on YouTube: Take WebElement Screenshot in Selenium 4
🎓 Key Takeaways
- Selenium 4 allows direct WebElement screenshot capture
- Use getScreenshotAs() method
- Timestamp prevents file overwrite
- Must implement screenshot in real-time automation frameworks
- Important Selenium interview topic
🚀 Created with ❤️ by Bhau Automation Lab