Is it possible to take a screenshot using Selenium WebDriver?
(Note: Not Selenium Remote Control)
I got this issue resolved. You can augment the RemoteWebDriver
to give it all of the interfaces its proxied driver implements:
WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); // It works this way
Set-Location PATH:\to\selenium
Add-Type -Path "Selenium.WebDriverBackedSelenium.dll"
Add-Type -Path "ThoughtWorks.Selenium.Core.dll"
Add-Type -Path "WebDriver.dll"
Add-Type -Path "WebDriver.Support.dll"
$driver = New-Object OpenQA.Selenium.PhantomJS.PhantomJSDriver
$driver.Navigate().GoToUrl("https://www.google.co.uk/")
# Take a screenshot and save it to filename
$filename = Join-Path (Get-Location).Path "01_GoogleLandingPage.png"
$screenshot = $driver.GetScreenshot()
$screenshot.SaveAsFile($filename, [System.Drawing.Imaging.ImageFormat]::Png)
Other drivers...
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver
$driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver
$driver = New-Object OpenQA.Selenium.IE.InternetExplorerDriver
$driver = New-Object OpenQA.Selenium.Opera.OperaDriver
It uses PHPUnit_Selenium extension version 1.2.7:
class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase {
...
public function screenshot($filepath) {
$filedata = $this->currentScreenshot();
file_put_contents($filepath, $filedata);
}
public function testSomething() {
$this->screenshot('/path/to/screenshot.png');
}
...
}
String yourfilepath = "E:\\username\\Selenium_Workspace\\foldername";
// Take a snapshort
File snapshort_file = ((TakesScreenshot) mWebDriver)
.getScreenshotAs(OutputType.FILE);
// Copy the file into folder
FileUtils.copyFile(snapshort_file, new File(yourfilepath));
You can use the following code snippet/function to take screenshot with 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);
}
You can create a webdriverbacked selenium object
using the Webdriver
class object, and then you can take a screenshot.