在 Selenium 中进行网页截图的最佳方法?


我们可以使用 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://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();
   }
}

更新时间: 2020 年 11 月 28 日

236 次浏览

开启你的 职业

完成课程获得认证

开始吧
广告
© . All rights reserved.