Selenium:如何在remotedriver C#中使用captureentirepagescreenshot

时间:2012-03-13 18:40:22

标签: selenium

在Selenium文档中,我可以看到如何拍摄正常的屏幕截图:

http://seleniumhq.org/docs/04_webdriver_advanced.html

但我想将captureentirepagescreenshot与远程webdriver一起使用,C#

这可能吗?任何例子?

2 个答案:

答案 0 :(得分:0)

请使用selenium webdriver 2.33版。下面的代码是一个c#代码,所以请从链接http://docs.seleniumhq.org/download/下载.net的selenium webdriver dll

Selenium webdriver具有内置功能,称为ITakesScreenshot,可以截取运行时。

请参阅以下代码

 `public static void SaveScreenShot(string screenshotFirstName)
    {
        var folderLocation = "Screenshot folder path";
        var screenshot = ((ITakesScreenshot)Driver).GetScreenshot();
        var filename = new StringBuilder(folderLocation);
        filename.Append(screenshotFirstName);
        filename.Append(DateTime.Now.ToString("dd-MM-yyyy HH_mm_ss"));\\append date and time
        filename.Append(".png"); \\append image extension
        screenshot.SaveAsFile(filename.ToString(), System.Drawing.Imaging.ImageFormat.Png);

    }`

希望这对你有用。

谢谢, Anshul

答案 1 :(得分:0)

如果您使用IWebDriver实现(例如InternetExplorerDriver,FirefoxDriver),您只需将其转换为ITakesScreenshot接口并使用GetScreenShot()方法:

IWebDriver driver = new InternetExplorerDriver();
Screenshot screenShot = ((ITakesScreenshot)driver).GetScreenshot();
screenShot.SaveAsFile(/*fullFileNameAndPath*/, ImageFormat.Png);

但是如果你想用RemoteWebDriver来做这件事,你不能,因为它没有实现ITakesScreenshot接口。因此,您必须基于实现此接口的RemoteWebDriver创建一个新类,并添加GetScreenshot()方法,例如:

public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
{
    public ScreenShotRemoteWebDriver(Uri RemoteAdress, ICapabilities capabilities)
        : base(RemoteAdress, capabilities) { }

    /// <summary>
    /// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
    /// </summary>
    /// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
    public Screenshot GetScreenshot()
    {
        // Get the screenshot as base64.
        Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
        string base64 = screenshotResponse.Value.ToString();

        // ... and convert it.
        return new Screenshot(base64);
    }       
}

现在您可以像使用IWebDriver一样使用它:

RemoteWebDriver driver = new ScreenShotRemoteWebDriver(/*uri*/, /*capabilities*/);
Screenshot screenShot = ((ITakesScreenshot)driver).GetScreenshot();
screenShot.SaveAsFile(/*fullFileNameAndPath*/, ImageFormat.Png);

我花了一些时间来理解驱动程序的类和接口的迷宫,但过了一段时间它才有意义。