Jak zrobić zrzut ekranu za pomocą Selenium WebDriver?

Czy można zrobić zrzut ekranu używając Selenium WebDriver?

(Uwaga: Nie Selenium Remote Control )

Author: Peter Mortensen, 2010-08-06

30 answers

Java

Tak, to możliwe. Poniższy przykład znajduje się w języku 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"));
 518
Author: Sergii Pozharov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:21:36

Python

Każdy WebDriver ma metodę .save_screenshot(filename). Tak więc dla Firefoksa można go używać w następujący sposób:

from selenium import webdriver

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

Co mylące, istnieje również metoda .get_screenshot_as_file(filename), która robi to samo.

Istnieją również metody: .get_screenshot_as_base64() (do osadzania w HTML) i .get_screenshot_as_png() (do pobierania danych binarnych).

I zauważ że WebElements ma metodę .screenshot(), która działa podobnie, ale przechwytuje tylko wybrany element.

 282
Author: Corey Goldberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-05 21:57:26

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;
    }
}
 112
Author: jessica,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:21:45

JavaScript (Selenium-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);
   });
});
 79
Author: Moiz Raja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:21:56

Ruby

require 'rubygems'
require 'selenium-webdriver'

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

Więcej typów plików i opcji jest dostępnych i można je zobaczyć w pliku takes_screenshot.rb .

 67
Author: sirclesam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-05 21:58:00

Java

Rozwiązałem ten problem. Możesz rozszerzyć RemoteWebDriver, aby dać mu wszystkie interfejsy, które implementuje jego proxy driver:
WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); // It works this way
 35
Author: user708910,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-05 22:00:00

PHP ( PHPUnit)

Używa rozszerzenia PHPUnit_Selenium w wersji 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');
    }
    ...
}
 34
Author: Ryan Mitchell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-05 22:07:06

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);
}
 26
Author: wsbaser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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;
}
 18
Author: SilverColt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:22:10

Jython

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"))
 12
Author: Fresh Mind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:22:26

Java ( Robot Framework)

Użyłem tej metody do robienia zrzutu ekranu.

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

Możesz używać tej metody wszędzie tam, gdzie jest to wymagane.

 10
Author: ank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-05 22:04:09

Java

Wydaje się tu brakować-wykonanie zrzutu ekranu określonego elementu w Javie:

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);
}
 8
Author: Erki M.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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();
        }
    }
}

Wymaga pakietów NuGet:

  1. PhantomJS 2.0.0
  2. Selen.Wsparcie 2.48.2
  3. Selen.WebDriver 2.48.2
[[3]} został przetestowany z. NET Framework v4. 5. 2.
 6
Author: userlond,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 21:31:02

Java

Nie udało mi się uzyskać zaakceptowanej odpowiedzi do pracy, ale zgodnie z aktualną dokumentacją WebDriver, następujące działania działały dobrze dla mnie z Java 7 na OS X v10. 9 (Mavericks):

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);
   }
}
 4
Author: Steve HHH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 18:43:18

Istnieje wiele metod za pomocą Selenium s Java i Python klienta, aby wykonać zrzut ekranu za pomocą Selenium WebDriver .


Metody Javy

Oto różne Java metody wykonania zrzutu ekranu :

  • Za pomocą getScreenshotAs() z interfejsu TakesScreenshot :

  • Kod blok:

         package screenShot;
    
         import java.io.File;
         import java.io.IOException;
    
         import org.apache.commons.io.FileUtils;
         import org.openqa.selenium.OutputType;
         import org.openqa.selenium.TakesScreenshot;
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         public class Firefox_takesScreenshot {
    
             public static void main(String[] args) throws IOException {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://login.bws.birst.com/login.html/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Birst"));
                 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                 FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Mads_Cruz_screenshot.png"));
                 driver.quit();
             }
         }
    
  • Zrzut ekranu:

    Mads_Cruz_screenshot

  • Jeśli strona jest włączona jQuery , możesz użyć ashot z pazone / ashot biblioteki:

  • Kod bloku:

         package screenShot;
    
         import java.io.File;
         import javax.imageio.ImageIO;
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         import ru.yandex.qatools.ashot.AShot;
         import ru.yandex.qatools.ashot.Screenshot;
         import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
    
         public class ashot_CompletePage_Firefox {
    
             public static void main(String[] args) throws Exception {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://jquery.com/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("jQuery"));
                 Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
                 ImageIO.write(myScreenshot.getImage(),"PNG",new File("./Screenshots/firefoxScreenshot.png"));
                 driver.quit();
             }
         }
    
  • Zrzut ekranu:

    firefoxScreenshot.png

  • Użycie Selenium-shutterbug z assertthat/selenium-shutterbug biblioteka:

  • Kod blok:

         package screenShot;
    
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import com.assertthat.selenium_shutterbug.core.Shutterbug;
         import com.assertthat.selenium_shutterbug.utils.web.ScrollStrategy;
    
         public class selenium_shutterbug_fullpage_firefox {
    
             public static void main(String[] args) {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://www.google.co.in");
                 Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save("./Screenshots/");
                 driver.quit();
             }
         }
    
  • Zrzut ekranu:

    2019_03_12_16_30_35_787.png


Metody Pythona

Oto różne Python metody wykonania zrzutu ekranu :

  • Za pomocą save_screenshot() "metoda": {]}

  • Kod bloku:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.save_screenshot('./Screenshots/save_screenshot_method.png')
         driver.quit()
    
  • Zrzut ekranu:

    save_screenshot_method.png

  • Korzystanie z get_screenshot_as_file() "metoda": {]}

  • Kod blok:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.get_screenshot_as_file('./Screenshots/get_screenshot_as_file_method.png')
         driver.quit()
    
  • Zrzut ekranu:

    get_screenshot_as_file_method.png

  • Za pomocą get_screenshot_as_png() "metoda": {]}

  • Kod bloku:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         screenPnG = driver.get_screenshot_as_png()
    
         # Crop it back to the window size (it may be taller)
         box = (0, 0, 1366, 728)
         im = Image.open(BytesIO(screenPnG))
         region = im.crop(box)
         region.save('./Screenshots/get_screenshot_as_png_method.png', 'PNG', optimize=True, quality=95)
         driver.quit()
    
  • Zrzut ekranu:

    get_screenshot_as_png_method.png

 4
Author: DebanjanB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 21:59:16

Rubin (Ogórek)

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
 3
Author: vijay chouhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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
 3
Author: vijay chouhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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));
    }
  }
 3
Author: Arpan Buch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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)
Inni kierowcy...
$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
 3
Author: TechSpud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:23:32

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
Author: dmeehan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:23:36

Java

Używając RemoteWebDriver, po powiększeniu węzła o możliwość zrzutu ekranu, zapisałbym zrzut ekranu w następujący sposób:

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

Możesz używać tej metody wszędzie tam, gdzie jest to wymagane. Następnie zakładam, że możesz dostosować arkusz stylów maven-surefire-report-plugin w Surefire-reports / html / custom.css, aby Twoje raporty zawierały link do prawidłowego zrzutu ekranu dla każdego testu?

 2
Author: djangofan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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));
 2
Author: Yerram Naveen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 18:43:46

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

Za pomocą tych dwóch metod można zrobić zrzut ekranu z datą i godziną, jak również.

 2
Author: Raghuveer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 18:45:01

Selenese

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
 2
Author: Bernát,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 19:21:56

Możesz spróbować do AShot API. To jest na GitHub.

Przykłady testów .

 2
Author: Khaja Mohammed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 21:28:02

C #

Możesz użyć poniższego fragmentu kodu/funkcji do zrobienia zrzutu ekranu za pomocą 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);
    }
 2
Author: Mohsin Awan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 21:32:52

Java

Metoda przechwytywania zrzutu ekranu dla błędów w Selenium z dołączoną nazwą testową i znacznikiem czasu.

public class Screenshot{
    final static String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
    public static String imgname = null;

    /*
     * Method to Capture Screenshot for the failures in Selenium with TestName and Timestamp appended.
     */
    public static void getSnapShot(WebDriver wb, String testcaseName) throws Exception {
      try {
      String imgpath = System.getProperty("user.dir").concat("\\Screenshot\\"+testcaseName);
      File f = new File(imgpath);
      if(!f.exists())   {
          f.mkdir();
        }
        Date d = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("dd_MM_yy_HH_mm_ss_a");
        String timestamp = sd.format(d);
        imgname = imgpath + "\\" + timestamp + ".png";

        // Snapshot code
        TakesScreenshot snpobj = ((TakesScreenshot)wb);
        File srcfile = snpobj.getScreenshotAs(OutputType.FILE);
        File destFile = new File(imgname);
        FileUtils.copyFile(srcfile, destFile);

      }
      catch(Exception e) {
          e.getMessage();
      }
   }
 2
Author: Anuj Teotia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-19 21:35:53

C #(Ranorex API)

public static void ClickButton()
{
    try
    {
        // code
    }
    catch (Exception e)
    {
        TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
        Report.Screenshot();
        throw (e);
    }
}
 1
Author: Benny Meade,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-14 11:23:16

Możesz utworzyć webdriverbacked selenium object za pomocą obiektu klasy Webdriver, a następnie wykonać zrzut ekranu.

 1
Author: RosAng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-05 22:02:37

Python

Możesz przechwycić obraz z systemu windows za pomocą sterownika internetowego Pythona. Użyj kodu poniżej, która strona musi zrobić zrzut ekranu.

driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')
 1
Author: Kv.senthilkumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-05 22:09:16