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

(注:不含硒遥控器)


当前回答

C#

using System;
using OpenQA.Selenium.PhantomJS;
using System.Drawing.Imaging;

namespace example.com
{
    class Program
    {
        public static PhantomJSDriver driver;

        public static void Main(string[] args)
        {
            driver = new PhantomJSDriver();
            driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);
            driver.Navigate().GoToUrl("http://www.example.com/");
            driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png);
            driver.Quit();
        }
    }
}

它需要NuGet包:

PhantomJS 2.0.0 硒。支持2.48.2 硒。WebDriver 2.48.2

它是用。net Framework v4.5.2测试的。

其他回答

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

}

你可以在浏览器中截取网页可见部分的截图:

首先导入:

import java.io.File;
import com.google.common.io.Files;

Then

File src=((TakesScreenshot)driver).getScreenShotAs(OutputType.FILE);
Files.copy(src,new File("new path/pic.jpeg"));

另外,在Selenium4之后,你还可以截取webelement的截图:

WebElement element=driver.findElement(By.xpath("xpath 
 here"));
File src=element.getScreenShotAs(OutputType.FILE);
File.copy(src,new File("new path/pic.jpeg"));

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;
}

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

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