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

(注:不含硒遥控器)


当前回答

C#

public static void TakeScreenshot(IWebDriver driver, String filename)
{
    // Take a screenshot and save it to filename
    Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
    screenshot.SaveAsFile(filename, ImageFormat.Png);
}

其他回答

/**
 * Take a screenshot and move to the given folder location.
 *
 * @param driver
 * @param folderLocation
 * @return screenShotFilePath
 */
public static String captureScreenshot(WebDriver driver, String folderLocation) {

    // Variable to store screenshot's file path.
    String screenShotFilePath = null;

    // Generate unique id for screen shot name.
    String uniqueId = UUID.randomUUID().toString().substring(31);

    if (driver != null) {

        // Generate screenshot as a file
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // New screenshot file path with having file name
        screenShotFilePath = folderLocation + File.separator + uniqueId + ".png";

        // Move file to the destination location.
        FileUtils.moveFile(scrFile, new File(screenShotFilePath));
    }

    return screenShotFilePath;
}

Python

webdriver.get_screenshot_as_file(filepath)

上述方法将截取屏幕截图,并将其作为文件存储在作为参数提供的位置中。

使用c#和MSTestframework, 这里我创建了一个静态方法。采取了一个路径,我可以将图像存储为jpeg格式。为了更清楚,我用当前正在执行的测试用例和失败的日期和时间来命名这些屏幕截图。

          /// <summary>
            /// This method is used to screen shot where test method failed 
            /// </summary>
            /// <param name="testCase">TestCaseName</param>
            public static void Capture(string testCase)
            {
                try
                {
                    StringBuilder path = new StringBuilder("C:/Logs/Screenshot/");
                    Constant.screenshot = ((ITakesScreenshot)Constant.browser).GetScreenshot();
                    string fileName = path.Append(string.Format(testCase + "-at-{0:yyyy-MM dd_hh-mm-ss}.jpeg", DateTime.Now)).ToString();
                    Constant.screenshot.SaveAsFile(fileName, ScreenshotImageFormat.Jpeg);
                }
                catch (Exception e)
                {
                    File.AppendAllText("C:/Logs/FailedTestCasesLogs.txt", "\nCOULD NOT CAPTURE THE SCREENSHOT!\n");
                    Log(e);
                }
    
            }

Java

使用RemoteWebDriver,在增加了节点的截图功能后,我将像这样存储截图:

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000);
        long id = Thread.currentThread().getId();
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(
            Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/"
            + id + "/screenshot.jpg"));
    }
    catch( Exception e ) {
        e.printStackTrace();
    }
}

你可以在任何需要的地方使用这种方法。然后,我假设您可以在surefire-reports/html/custom.css中定制maven-surefire-report-plugin的样式表,以便您的报告包含到每个测试的正确截图的链接。

Python

每个WebDriver都有一个. save_截图(filename)方法。所以对于Firefox,它可以这样使用:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')

令人困惑的是,.get_screenshot_as_file(filename)方法也存在,它做同样的事情。

还有一些方法:.get_screenshot_as_base64()(用于嵌入HTML)和.get_screenshot_as_png()(用于检索二进制数据)。

注意,WebElements有一个.截图()方法,它的工作原理类似,但只捕获所选元素。