是否可以使用Selenium WebDriver进行截图?

(注:不含硒遥控器)


当前回答

import java.io.File;
import java.io.IOException;

import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
 * @author Jagdeep Jain
 *
 */
public class ScreenShotMaker {

    // take screen shot on the test failures
    public void takeScreenShot(WebDriver driver, String fileName) {
        File screenShot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));

        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        }
    }

}

其他回答

C#

public Bitmap TakeScreenshot(By by) {
    // 1. Make screenshot of all screen
    var screenshotDriver = _selenium as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));

    // 2. Get screenshot of specific element
    IWebElement element = FindElement(by);
    var cropArea = new Rectangle(element.Location, element.Size);
    return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}

Ruby(黄瓜)

After do |scenario| 
    if(scenario.failed?)
        puts "after step is executed"
    end
    time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')

    file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'

    page.driver.browser.save_screenshot file_path
end

Given /^snapshot$/ do
    time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')

    file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'
    page.driver.browser.save_screenshot file_path
end
import java.io.File;
import java.io.IOException;

import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
 * @author Jagdeep Jain
 *
 */
public class ScreenShotMaker {

    // take screen shot on the test failures
    public void takeScreenShot(WebDriver driver, String fileName) {
        File screenShot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));

        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        }
    }

}

更新2022

要在Selenium中截取屏幕截图,我们使用一个名为TakesScreenshot的接口,它使Selenium WebDriver能够捕捉屏幕截图并以不同的方式存储它。它有一个getScreenshotAs()方法,用于捕获屏幕截图并将其存储在指定的位置。

//Convert webdriver to TakeScreenshot
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

在上面的代码中,它将WebDriver对象(驱动程序)转换为TakeScreenshot。并调用getScreenshotAs()方法通过提供参数*OutputType.FILE来创建图像文件。

我们可以使用File对象将图像复制到我们想要的位置,如下所示,使用FileUtils类。

FileUtils.copyFile(screenshotFile , new File("C:\\temp\\screenshot.png));

捕获整个页面

Selenium WebDriver没有提供捕获整个页面截图的固有功能。为了捕获整个页面的截图,我们必须使用一个名为shot的第三方库。它提供了截取特定WebElement的截图以及整页截图的功能。

捕获屏幕大小的图像

Screenshot screenshot = new Ashot().takeScreenshot(driver);

捕获整个页面的截图

Screenshot s=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(s.getImage(),"PNG",new File("<< file path>>"));

在上面的代码中,1000是以毫秒为单位的滚动时间。换句话说,这意味着该程序将滚动每1000毫秒来截取屏幕截图。

捕获一个元素

在Selenium中有两种方法来捕获web元素的屏幕截图。

取全屏图像,然后根据网页元素的尺寸裁剪图像。 在web元素上使用getScreenshotAs()方法。(这只在selenium版本4.X中可用)

Java

我想我应该给出完整的解决方案,因为有两种不同的方法获得截图。一个来自本地浏览器,另一个来自远程浏览器。我甚至将图像嵌入到HTML报告中:

@After()
public void selenium_after_step(Scenario scenario) throws IOException, JSONException {

    if (scenario.isFailed()){

        scenario.write("Current URL = " + driver.getCurrentUrl() + "\n");

        try{
            driver.manage().window().maximize();  // Maximize window to get full screen for chrome
        }
        catch (org.openqa.selenium.WebDriverException e){
            System.out.println(e.getMessage());
        }

        try {
            if(isAlertPresent()){
                Alert alert = getAlertIfPresent();
                alert.accept();
            }
            byte[] screenshot;
            if(false /*Remote Driver flow*/) { // Get a screenshot from the remote driver
                Augmenter augmenter = new Augmenter();
                TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver);
                screenshot = ts.getScreenshotAs(OutputType.BYTES);
            } 
            else { // Get a screenshot from the local driver
                // Local webdriver user flow
                screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            }
            scenario.embed(screenshot, "image/png"); // Embed the image in reports
        } 
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } 
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }

    //seleniumCleanup();
}