Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chụp màn hình (Screenshot) mô phỏng phím Print Screen với Selenium WebDriver Java

Selenium cho phép chụp ảnh màn hình trình duyệt thông qua interface TakesScreenshot. Đây là kỹ thuật quan trọng cho debug, báo cáo lỗi, và test evidence.

Các bước thực hiện

  1. Ép kiểu driver sang TakesScreenshot.
  2. Gọi getScreenshotAs(OutputType.FILE) để lấy file ảnh.
  3. Sao chép file đến vị trí mong muốn bằng FileUtils.copyFile() (cần thư viện Apache Commons IO).

Cú pháp

TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("path/to/screenshot.png"));

Ví dụ hoàn chỉnh

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;

public class ScreenshotExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        
        try {
            driver.get("https://www.example.com");
            
            // Chụp màn hình
            File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            File dest = new File("screenshots/homepage_" + System.currentTimeMillis() + ".png");
            FileUtils.copyFile(src, dest);
            
            System.out.println("Đã lưu screenshot: " + dest.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.quit();
        }
    }
}

Các định dạng OutputType khác

  • OutputType.FILE – trả về File (phổ biến nhất).
  • OutputType.BYTES – trả về byte[] (dùng cho attach vào report, email).
  • OutputType.BASE64 – trả về chuỗi Base64 (nhúng vào HTML report, log).

Chụp ảnh element cụ thể (Selenium 4+)

WebElement element = driver.findElement(By.id("logo"));
File src = element.getScreenshotAs(OutputType.FILE); // Chỉ chụp element đó
FileUtils.copyFile(src, new File("element_screenshot.png"));

Best Practices

  • Tạo thư mục screenshot tự động theo ngày/test case.
  • Đặt tên file có timestamp hoặc test name để tránh ghi đè.
  • Chụp screenshot khi test fail (dùng TestNG ITestListener hoặc JUnit TestWatcher).
  • Xóa screenshot cũ định kỳ để tiết ổ đĩa.

Phụ thuộc Maven (Apache Commons IO)

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>