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

(注:不含硒遥控器)


当前回答

PowerShell

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)

其他司机……

$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

其他回答

c#代码

IWebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((ITakesScreenshot)driver).GetScreenshotAs(OutputType.FILE);

// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

硒化/ Java

以下是Selenide项目是如何做到这一点的,这比任何其他方式都要简单:

import static com.codeborne.selenide.Selenide.screenshot;    
screenshot("my_file_name");

JUnit:

@Rule
public ScreenShooter makeScreenshotOnFailure = 
     ScreenShooter.failedTests().succeededTests();

美国小妞TestNG:

import com.codeborne.selenide.testng.ScreenShooter;
@Listeners({ ScreenShooter.class})

机器人框架

下面是一个使用Robot Framework和Selenium2Library的解决方案:

*** Settings ***
Library                        Selenium2Library

*** Test Cases ***
Example
    Open Browser               http://localhost:8080/index.html     firefox
    Capture Page Screenshot

这将在工作空间中保存一个截图。也可以为关键字Capture Page截图提供一个文件名来改变这种行为。

塞勒尼斯

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd

PHP

public function takescreenshot($event)
  {
    $errorFolder = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "ErrorScreenshot";

    if(!file_exists($errorFolder)){
      mkdir($errorFolder);
    }

    if (4 === $event->getResult()) {
      $driver = $this->getSession()->getDriver();
      $screenshot = $driver->getWebDriverSession()->screenshot();
      file_put_contents($errorFolder . DIRECTORY_SEPARATOR . 'Error_' .  time() . '.png', base64_decode($screenshot));
    }
  }