Prenez une capture d'écran avec Selenium WebDriver

est-ce que quelqu'un sait s'il est possible de prendre une capture d'écran en utilisant Selenium WebDriver? (Note: Pas de sélénium RC)

431
demandé sur user1 2010-08-06 12:52:18

30 réponses

Java

Oui, c'est possible. L'exemple suivant est en Java:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)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"));
441
répondu Sergii Pozharov 2015-11-14 11:21:36

Python

chaque WebDriver a une méthode .save_screenshot(filename) . Donc pour Firefox, il peut être utilisé comme ceci:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')
browser.quit()

de façon confuse, une méthode .get_screenshot_as_file(filename) existe aussi qui fait la même chose.

il existe également des méthodes pour: .get_screenshot_as_base64() (pour l'intégration en html) et .get_screenshot_as_png() (pour l'extraction de données binaires).

et notez que WebElements ont une méthode .screenshot() qui fonctionne de la même façon, mais seulement capte l'élément sélectionné.

220
répondu Corey Goldberg 2015-12-09 09:53:19

c#

public void TakeScreenshot()
{
    try
    {            
        Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
        ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        throw;
    }
}
89
répondu jessica 2015-11-14 11:21:45

Ruby

require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :ie 
driver.get "https://www.google.com"   
driver.save_screenshot("./screen.png")

plus de types de fichiers et d'options sont disponibles et vous pouvez les voir dans takes_screenshot.rb

57
répondu sirclesam 2015-11-14 11:21:47

JavaScript (Sélénium, Le Webdriver)

driver.takeScreenshot().then(function(data){
   var base64Data = data.replace(/^data:image\/png;base64,/,"")
   fs.writeFile("out.png", base64Data, 'base64', function(err) {
        if(err) console.log(err);
   });
});
57
répondu Moiz Raja 2015-11-14 11:21:56

Java

j'ai résolu ce problème. Vous pouvez augmenter le RemoteWebDriver pour lui donner toutes les interfaces que son pilote proxied met en œuvre:

WebDriver augmentedDriver = new Augmenter().augment(driver); 
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); //works this way
31
répondu user708910 2015-11-14 11:21:55

PHP (PHPUnit)

utilise l'extension PHPUnit_Selenium 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');
    }
    ...
}
31
répondu Ryan Mitchell 2015-11-14 11:21:59

c#

public Bitmap TakeScreenshot(By by) {
    // 1. Make screenshot of all screen
    var screenshotDriver = _selenium as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));

    // 2. Get screenshot of specific element
    IWebElement element = FindElement(by);
    var cropArea = new Rectangle(element.Location, element.Size);
    return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}
18
répondu wsbaser 2015-11-14 11:22:15

Java

public String captureScreen() {
    String path;
    try {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
        path = "./target/screenshots/" + source.getName();
        FileUtils.copyFile(source, new File(path)); 
    }
    catch(IOException e) {
        path = "Failed to capture screenshot: " + e.getMessage();
    }
    return path;
}
15
répondu SilverColt 2015-11-14 11:22:10

Python

import org.openqa.selenium.OutputType as OutputType
import org.apache.commons.io.FileUtils as FileUtils
import java.io.File as File
import org.openqa.selenium.firefox.FirefoxDriver as FirefoxDriver

self.driver = FirefoxDriver()
tempfile = self.driver.getScreenshotAs(OutputType.FILE)
FileUtils.copyFile(tempfile, File("C:\screenshot.png"))
10
répondu Fresh Mind 2015-11-14 11:22:26

Java (Robot Framework)

j'ai utilisé cette méthode pour la prise de vue à l'écran.

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000)
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg"));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

vous pouvez utiliser cette méthode si nécessaire.

8
répondu ank 2015-11-14 11:22:12

Java

semble manquer ici-capture d'écran d'un élément spécifique en Java:

public void takeScreenshotElement(WebElement element) throws IOException {
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
    Point location = element.getLocation();
    BufferedImage bufferedImage = ImageIO.read(screenshot);
    BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
    ImageIO.write(destImage, "png", screenshot);
    File file = new File("//path//to");
    FileUtils.copyFile(screenshot, file);
}
6
répondu Erki M. 2015-11-14 11:22:36

c#

using System;
using OpenQA.Selenium.PhantomJS;
using System.Drawing.Imaging;

namespace example.com
{
    class Program
    {
        public static PhantomJSDriver driver;

        public static void Main(string[] args)
        {
            driver = new PhantomJSDriver();
            driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);
            driver.Navigate().GoToUrl("http://www.example.com/");
            driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png);
            driver.Quit();
        }
    }
}

Nécessite NuGetPackages:

  1. PhantomJS 2.0.0
  2. sélénium.Soutien 2.48.2
  3. sélénium.WebDriver 2.48.2

Testé avec .Netfram framework v4.5.2

6
répondu userlond 2016-06-08 00:12:32

Java

Je n'ai pas pu obtenir la réponse acceptée pour travailler, mais comme dans la documentation actuelle de WebDriver , ce qui suit a fonctionné très bien pour moi avec Java 7 sur OS X 10.9:

import java.io.File;
import java.net.URL;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

   public void myTest() throws Exception {
       WebDriver driver = new RemoteWebDriver(
               new URL("http://localhost:4444/wd/hub"),
               DesiredCapabilities.firefox());

       driver.get("http://www.google.com");

       // RemoteWebDriver does not implement the TakesScreenshot class
       // if the driver does have the Capabilities to take a screenshot
       // then Augmenter will add the TakesScreenshot methods to the instance
       WebDriver augmentedDriver = new Augmenter().augment(driver);
       File screenshot = ((TakesScreenshot)augmentedDriver).
               getScreenshotAs(OutputType.FILE);
   }
}
5
répondu Steve HHH 2015-11-14 11:22:33

Ruby (Concombre)

After do |scenario| 
    if(scenario.failed?)
        puts "after step is executed"
    end
    time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')

    file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'

    page.driver.browser.save_screenshot file_path
end

Given /^snapshot$/ do
    time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')

    file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'
    page.driver.browser.save_screenshot file_path
end
4
répondu vijay chouhan 2015-11-14 11:22:57

Ruby

time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M_%S')
file_path = File.expand_path(File.dirname(__FILE__) + 'screens_shot')+'/'+time +'.png'
#driver.save_screenshot(file_path)
page.driver.browser.save_screenshot file_path
4
répondu vijay chouhan 2015-11-14 11:23:04

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));
    }
  }
4
répondu Arpan Buch 2015-11-14 11:23:07

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)

autres conducteurs...

$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
4
répondu TechSpud 2015-11-14 11:23:32

Python

vous pouvez capturer l'image depuis windows en utilisant le pilote web python. Utilisez le code ci-dessous quelle page doit capturer la capture d'écran

driver.save_screenshot('c:\foldername\filename.extension(png,jpeg)')
3
répondu Kv.senthilkumar 2015-11-14 11:22:30

c#

public static void TakeScreenshot(IWebDriver driver, String filename)
{
    // Take a screenshot and save it to filename
    Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
    screenshot.SaveAsFile(filename, ImageFormat.Png);
}
3
répondu dmeehan 2015-11-14 11:23:36

Java

public  void captureScreenShot(String obj) throws IOException {
    File screenshotFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshotFile,new File("Screenshots\"+obj+""+GetTimeStampValue()+".png"));
}

public  String GetTimeStampValue()throws IOException{
    Calendar cal = Calendar.getInstance();       
    Date time=cal.getTime();
    String timestamp=time.toString();
    System.out.println(timestamp);
    String systime=timestamp.replace(":", "-");
    System.out.println(systime);
    return systime;
}

en utilisant ces deux méthodes, vous pouvez prendre une capture d'écran avec la date et l'heure ainsi.

2
répondu Raghuveer 2015-11-14 11:22:53

Java

en utilisant RemoteWebDriver, après avoir augmenté le noeud avec la capacité de capture d'écran, je stockerais la capture d'écran comme ceci:

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000);
        long id = Thread.currentThread().getId();
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(
            Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/"
            + id + "/screenshot.jpg"));
    }
    catch( Exception e ) {
        e.printStackTrace();
    }
}

vous pouvez utiliser cette méthode si nécessaire. Ensuite, je suppose que vous pouvez personnaliser la feuille de style de maven-surefire-rapport-plugin à surefire-rapports/html/custom.css afin que vos rapports incluent le lien vers la capture d'écran correcte pour chaque test?

2
répondu djangofan 2015-11-14 11:23:01

Java

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));

Espère que cela résout votre problème

2
répondu Yerram Naveen 2015-11-14 11:23:21

Sélénèse

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
2
répondu Bernát 2015-11-14 11:23:39

c#

vous pouvez utiliser le code suivant snippet / fonction pour prendre la capture d'écran avec le sélénium:

    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);
    }
2
répondu Mohsin Awan 2016-12-10 16:19:32

vous pouvez donner un essai à AShot API. Voici le lien github pour le même.

https://github.com/yandex-qatools/ashot

quelques-uns des tests ici...

https://github.com/yandex-qatools/ashot/tree/master/src/test/java/ru/yandex/qatools/elementscompare/tests

2
répondu Khaja Mohammed 2017-02-24 05:28:11

C# (Ranorex API)

public static void ClickButton()
{
    try
    {
        // code
    }
    catch (Exception e)
    {
        TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
        Report.Screenshot();
        throw (e);
    }
}
1
répondu Benny Meade 2015-11-14 11:23:16

Python

def test_url(self):
    self.driver.get("https://www.google.com/")
    self.driver.save_screenshot("test.jpg")

il sauvera screenshot dans le même répertoire où le script est sauvé.

1
répondu Hemant 2015-11-14 11:23:19

Java

, Pensais-je donnerais mon solution complète puisqu'il y a deux façons différentes d'obtenir une capture d'écran. L'une provient du navigateur local, et l'autre du navigateur distant. J'ai même intégré l'image dans le rapport html

@After()
public void selenium_after_step(Scenario scenario) throws IOException, JSONException {

    if (scenario.isFailed()){

        scenario.write("Current URL = " + driver.getCurrentUrl() + "\n");

        try{
            driver.manage().window().maximize();  //Maximize window to get full screen for chrome
        }catch (org.openqa.selenium.WebDriverException e){

            System.out.println(e.getMessage());
        }

        try {
            if(isAlertPresent()){
                Alert alert = getAlertIfPresent();
                alert.accept();
            }
            byte[] screenshot;
            if(false /*Remote Driver flow*/) { //Get Screen shot from remote driver
                Augmenter augmenter = new Augmenter();
                TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver);
                screenshot = ts.getScreenshotAs(OutputType.BYTES);
            } else { //get screen shot from local driver
                //local webdriver user flow
                screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            }
            scenario.embed(screenshot, "image/png"); //Embed image in reports
        } catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }

    //seleniumCleanup();
}
1
répondu Jason Smiley 2015-11-14 11:23:45

Sélénide / Java

Voici comment le Sélénide projet le fait, rendant plus facile que tout autre moyen de le faire:

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

Pour Junit:

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

Pour TestNG:

import com.codeborne.selenide.testng.ScreenShooter;
@Listeners({ ScreenShooter.class})
1
répondu djangofan 2015-11-16 21:01:32