我需要一种方法来截取我的功能测试的屏幕截图。现在我正在使用带有 C# 绑定的 Selenium 2。我非常想在测试结束时截屏以确保显示所需的页面。你们知道我可以将哪些特定工具合并到我的 C# 代码中来触发屏幕截图吗?我找不到内置的 Selenium 2 解决方案(不仔细看)。
13 回答
要在 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
var driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
var ss = driver.GetScreenshot();
ss.SaveAsFile("ss.png", System.Drawing.Imaging.ImageFormat.Png);
我不知道这是否重要,但是当我用 c# 编写代码时,我最终不得不强制转换驱动程序。
就像是:
截图 ss = ((ITakesScreenshot)driver).GetScreenshot();
只需在一行代码中使用扩展方法 TakeScreenshot() 即可。
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("Your_Homepage_Url");
driver.TakeScreenshot().SaveAsFile("file_name_string", ImageFormat.Jpeg);
System.Drawing
在您的解决方案/项目中添加参考。System.Drawing.Imaging
在测试中使用命名空间。
在这里,我正在捕获 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;
}
}
}
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);
}
此代码将帮助您拍摄屏幕截图
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
使用 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)你会在截图时知道完美的日期时间。2) SaveAsFile 函数覆盖现有文件。因此,DateTime 可以帮助创建不同的文件。
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();
在这里试试这个代码......希望它对你有用......!
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");
在全局代码中定义:
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"));
在 python 中以通用方式截取屏幕截图并存储在文件位置的最佳方法:
def screenShots(self):
fileName= NewFile + "." + str(round(time.time() * 1000)) + ".png"
screenshotDirectory = "../screenshot/" #Move to that directory where you want ot store the screenshot
relativeFileName = screenshotDirectory + fileName
currentDirectory = os.path.dirname(__file__)
destinationFile = os.path.join(currentDirectory,relativeFileName)
destinationDirectory = os.path.join(currentDirectory,screenshotDirectory)
try:
if not os.path.exists(destinationDirectory):
os.makedirs(destinationDirectory)
self.driver.save_screenshot(destinationFile)
self.log.info("Screenshot saved to directory" + destinationFile)
except:
self.log.error("Exception Occured")
print_stack()
使用 selenium 有两个我熟悉的调用:captureEntirePageScreenshot
和captureScreenshot
. 您可能想查看这些调用,看看它们是否会完成您所追求的目标。