将网页截图导入 Selenium 的最佳方法是什么?

software testingautomation testingselenium web driver更新于 2026/2/8 6:07:17

我们可以使用 Selenium 截取网页截图。这是一个三步过程。截图是缺陷和故障分析中最重要的步骤之一。

首先,我们必须将驱动程序对象转换为 TakeScreenshot 接口。

语法

TakesScreenshot s = (TakesScreenshot)driver;

接下来,我们必须借助 getScreenshotAs 方法获取图像文件,最后使用 FileUtils.copyFile 方法将文件复制到某个位置。

语法

File src=s.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("file path"));

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ScreenshotCapture{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // screenshot capturing
      File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(src, new File("careerpage.png"));
      driver.quit();
   }
}

相关文章