การจับภาพหน้าจอ (Screenshot) ใน Selenium ทำได้ผ่าน interface TakesScreenshot เป็นกระบวนการ 3 ขั้นตอน:
- Cast driver เป็น
TakesScreenshot - เรียก
getScreenshotAs(OutputType.FILE)ได้ไฟล์รูปภาพ - คัดลอกไฟล์ไปยังตำแหน่งที่ต้องการด้วย
FileUtils.copyFile()
Syntax
// 1. Cast driver
TakesScreenshot screenshot = (TakesScreenshot) driver;
// 2. ได้ไฟล์รูปภาพ
File srcFile = screenshot.getScreenshotAs(OutputType.FILE);
// 3. บันทึกไฟล์
FileUtils.copyFile(srcFile, new File("path/to/screenshot.png"));
ตัวอย่างโค้ดสมบูรณ์
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class ScreenshotExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
try {
driver.get("https://www.tutorialspoint.com/index.htm");
// จับภาพหน้าจอ
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// บันทึกไฟล์
File destFile = new File("screenshot_homepage.png");
FileUtils.copyFile(srcFile, destFile);
System.out.println("Screenshot saved to: " + destFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
การจับภาพเฉพาะ Element (Element Screenshot) - Selenium 4+
// Selenium 4 มีเมธอด getScreenshotAs ตรงบน WebElement
WebElement element = driver.findElement(By.id("login-form"));
File elementScreenshot = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementScreenshot, new File("element_screenshot.png"));
การจับภาพแบบ Base64 String (สำหรับรายงาน/Embed ใน HTML)
String base64Screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
// สามารถนำไปใส่ใน HTML report ได้เลย: <img src="data:image/png;base64,${base64Screenshot}" />
Dependencies ที่ต้องมี (Maven)
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Best Practices
- จับภาพเมื่อ test fail (ใน @AfterMethod หรือ Listener)
- ตั้งชื่อไฟล์ด้วย timestamp เพื่อไม่ให้ทับกัน
- ล้าง screenshot เก่าๆ ให้เป็นระยะ เพื่อไม่ให้ disk เต็ม
- ใช้
OutputType.BASE64สำหรับรายงาน HTML (Allure, ExtentReports)
ตัวอย่าง: จับภาพเมื่อ Test Fail (TestNG Listener)
public class ScreenshotListener implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
WebDriver driver = ((WebDriver) result.getTestContext().getAttribute("driver"));
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String name = result.getMethod().getMethodName() + "_" + System.currentTimeMillis() + ".png";
try {
FileUtils.copyFile(src, new File("screenshots/" + name));
} catch (IOException e) {
e.printStackTrace();
}
}
}