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

(注:不含硒遥控器)


当前回答

Java

public void captureScreenShot(String obj) throws IOException {
    File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshotFile, new File("Screenshots\\" + obj + "" + GetTimeStampValue() + ".png"));
}

public String GetTimeStampValue()throws IOException{
    Calendar cal = Calendar.getInstance();
    Date time = cal.getTime();
    String timestamp = time.toString();
    System.out.println(timestamp);
    String systime = timestamp.replace(":", "-");
    System.out.println(systime);
    return systime;
}

使用这两种方法,您还可以拍摄带有日期和时间的屏幕截图。

其他回答

Ruby

require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")

更多的文件类型和选项可用,您可以在文件takes_screenshot.rb中看到它们。

JavaScript (Selenium-Webdriver)

driver.takeScreenshot().then(function(data){
   var base64Data = data.replace(/^data:image\/png;base64,/,"")
   fs.writeFile("out.png", base64Data, 'base64', function(err) {
        if(err) console.log(err);
   });
});

使用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);
                }
    
            }

C#

你可以使用下面的代码片段/函数用Selenium截图:

    public void TakeScreenshot(IWebDriver driver, string path = @"output")
    {
        var cantakescreenshot = (driver as ITakesScreenshot) != null;
        if (!cantakescreenshot)
            return;
        var filename = string.Empty + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
        filename = path + @"\" + filename + ".png";
        var ss = ((ITakesScreenshot)driver).GetScreenshot();
        var screenshot = ss.AsBase64EncodedString;
        byte[] screenshotAsByteArray = ss.AsByteArray;
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        ss.SaveAsFile(filename, ImageFormat.Png);
    }

是的,可以使用Selenium WebDriver对网页进行快照。

WebDriver API提供的getScreenshotAs()方法为我们做了这项工作。

语法:getScreenshotAs(OutputType<X> target)

返回类型:X

参数:target—查看OutputType提供的选项

适用性:不特定于任何DOM元素

例子:

    TakesScreenshot screenshot = (TakesScreenshot) driver;
    File file = screenshot.getScreenshotAs(OutputType.FILE);

有关详细信息,请参阅下面的工作代码片段。

    public class TakeScreenShotDemo {

        public static void main(String[] args) {
            WebDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.get(“http: //www.google.com”);

            TakesScreenshot screenshot = (TakesScreenshot) driver;

            File file = screenshot.getScreenshotAs(OutputType.FILE);

            // Creating a destination file
            File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
            try {
                FileUtils.copyFile(file, destination);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

访问Snapshot using WebDriver获取更多详细信息。