在Selenium 2中截取测试截图的最佳方法是什么?

时间:2010-07-27 17:04:29

标签: c# selenium screenshot functional-testing webdriver

我需要一种方法来截取我的功能测试。现在我正在使用Selenium 2和C#绑定。我非常想在测试结束时截取屏幕截图,以确保显示所需的页面。您是否知道我可以将任何特定工具合并到我的C#代码中以触发屏幕截图?我找不到内置的Selenium 2解决方案(没有查看)。

13 个答案:

答案 0 :(得分:63)

要在Selenium 2中执行屏幕截图,您需要执行以下操作

driver = new FireFoxDriver(); // Should work in other Browser Drivers
driver.Navigate().GoToUrl("http://www.theautomatedtester.co.uk");
Screenshot ss = ((ITakesScreenshot) driver).GetScreenshot();

//Use it as you want now
string screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
ss.SaveAsFile("filename", ImageFormat.Png); //use any of the built in image formating
ss.ToString();//same as string screenshot = ss.AsBase64EncodedString;

该代码应该可以工作,因为我在IronPython Repl中快速测试了它。请参阅下面的IronPython代码

import clr
clr.AddReference("WebDriver.Common.dll")
clr.AddReference("WebDriver.Firefox.dll")
from OpenQA.Selenium import *
from OpenQA.Selenium.Firefox import *
driver = FirefoxDriver()
driver.Navigate().GoToUrl("http://www.theautomatedtester.co.uk")
s = driver.GetScreenshot()
s.AsBaseEncodedString
# HUGE string appears in the REPL

答案 1 :(得分:31)

var driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
var ss = driver.GetScreenshot();   
ss.SaveAsFile("ss.png", System.Drawing.Imaging.ImageFormat.Png);

答案 2 :(得分:12)

我不知道这是否重要,但当我用c#写作时,我最终不得不施展司机。

类似的东西:

Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();

答案 3 :(得分:6)

只需在一行代码中使用扩展方法TakeScreenshot()。

IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("Your_Homepage_Url");

driver.TakeScreenshot().SaveAsFile("file_name_string", ImageFormat.Jpeg);

答案 4 :(得分:2)

  1. 在您的解决方案/项目中添加System.Drawing的引用。
  2. 在测试中使用System.Drawing.Imaging命名空间。
  3. 我在这里捕捉Facebook主页的屏幕截图。

    using System;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium.Support.UI;
    using NUnit.Framework;
    using System.IO;
    using System.Collections;
    using System.Drawing.Imaging;
    
    namespace FacebookRegistrationUsingC_Sharp
    {
        [TestFixture]
        public class ScreenShot
        {
            IWebDriver driver = null;
            IWebElement element = null;
    
            [SetUp]
            public void SetUp()
            {
                driver = new ChromeDriver("G:\\Selenium_Csharp\\Jar\\chromedriver_win32");           
                driver.Navigate().GoToUrl("https://www.Facebook.com");
                driver.Manage().Window.Maximize();
    
            }
            [Test]
            public void TestScreenShot()
            {           
    
                Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
                ss.SaveAsFile("e:\\pande", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
    
            [TearDown]
            public void TearDown()
            {
                driver = null;
                element = null;
            }
        }
    }
    

答案 5 :(得分:1)

public void TakeScreenshot(string saveLocation) {
        var location = GetPath() + _name + "\\" + saveLocation + ".png";
        var ssdriver = _driver as ITakesScreenshot;
        var screenshot = ssdriver.GetScreenshot();
        screenshot.SaveAsFile(location, ImageFormat.Png);
    }

此代码将帮助您拍摄屏幕截图

答案 6 :(得分:1)

<强> JAVA

protected void fullPageScreenshot(String testname) {
            String timeStamp = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss").format(Calendar.getInstance().getTime());
            String imageName = testname + "-" + timeStamp + ".png";
            Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(2000))
                    .takeScreenshot(DriverManager.getDriver());
            try {
                ImageIO.write(screenshot.getImage(), "PNG", new File("./FullPage_Screenshots/" + imageName));
            } catch (Exception e) {
                System.out.println("Capturing FullPage Screenshot failed");
            }
        }

使用Ashot库获取全页截图 - 即使页面需要滚动 https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot/1.5.4

答案 7 :(得分:0)

使用System.Drawing.Imaging参考。 以下代码可用于截屏。

IWebDriver driver = new FirefoxDriver();
ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
String fp = "D:\\" + "snapshot" + "_"+ DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt") + ".png";
screenshot.SaveAsFile(fp, ImageFormat.Png);

注意: 时间戳有两个优点: 1)截取屏幕截图时,您将了解完美的DateTime。 2)SaveAsFile函数覆盖现有文件。因此,DateTime可以帮助创建不同的文件。

答案 8 :(得分:0)

        ScreenCaptureJob scj;
        scj = new ScreenCaptureJob();
        // Specify the path & file name in which you want to save         
        scj.OutputScreenCaptureFileName = @"C:\Users\jpavankumar\Desktop\Screencaptuere\ScreenRecording4.wmv";
        // Start the Screen Capture Job
        scj.Start(); scj.Stop();

在这里尝试这个代码......希望它对你有用......!

答案 9 :(得分:0)

driver.Url = "https://www.amazon.in/";
//Store image in bin folder
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile("CurrentPage.png"); 
//Store image in D drive        
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(@"D:\CurrentPage.png");

答案 10 :(得分:0)

在全局代码中定义:

var counter = DateTime.Now.Ticks.ToString();

((ITakesScreenshot)driver).GetScreenshot().SaveAsFile((snap +counter + ".jpg").ToString(), OpenQA.Selenium.ScreenshotImageFormat.Jpeg);
test.Log(LogStatus.Fail, "Snapshot below: " + test.AddScreenCapture(snap + counter + ".jpg"));

答案 11 :(得分:0)

在python中以通用方式获取屏幕快照并将其存储在文件位置的最佳方法:

class User(object):
    fname = ''
    mname = ''
    lname = ''

    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

user1 = User(fname='Foo', lname='Bar')
user2 = User(lname='Public', fname='John')
user2.mname = 'Q'

print(f"{user1.fname} {user1.mname} {user1.lname}")   # prints "Foo  Bar"
print(f"{user2.fname} {user2.mname} {user2.lname}")   # prints "John Q Public"

答案 12 :(得分:-1)

使用硒有两个我熟悉的电话:captureEntirePageScreenshotcaptureScreenshot。您可能希望查看这些调用,看看它们是否能完成您所追求的目标。