【问题标题】:How can I take a screenshot with Selenium WebDriver?如何使用 Selenium WebDriver 截屏?
【发布时间】:2011-03-26 05:39:04
【问题描述】:

是否可以使用 Selenium WebDriver 截屏?

(注意:不是Selenium Remote Control

【问题讨论】:

  • 使用 WebDriver Wire Protocol 可能只有一种方法可以做到这一点,但没有人直接使用此协议。相反,人们使用包装低级协议的不同语言绑定/库。有很多语言绑定,所以你需要说出你想使用哪一个。否则,答案太多了。
  • 您使用哪种编程语言?
  • 您要截取整个页面还是特定元素?
  • 是的,可以使用 Selenium WebDriver 截取整个页面或特定元素的屏幕截图

标签: selenium selenium-webdriver ashot takesscreenshot selenium-shutterbug


【解决方案1】:

Java

是的,这是可能的。下面的例子是用 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"));

【讨论】:

  • 如果源和目标可能不在同一个文件系统上,那么复制文件而不是重命名文件是个好主意。您不能跨文件系统边界重命名(至少在 unix 上)。请注意,/tmp 位于自己的文件系统上是很常见的,FirefoxDriver 会将屏幕截图写入/tmp
  • 有没有办法只针对失败的案例?
  • 值得注意的是HtmlUnitDriver 没有实现TakesScreenshot(有关支持的驱动程序列表,请参阅selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/…)。但你可以另存为 HTML。
  • 使用 FileUtils 类需要导入什么包?
  • @RiponAlWasim 可能是org.apache.commons.io.FileUtils
【解决方案2】:

Python

每个 WebDriver 都有一个 .save_screenshot(filename) 方法。所以对于 Firefox,可以这样使用:

from selenium import webdriver

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

令人困惑的是,还有一个 .get_screenshot_as_file(filename) 方法可以做同样的事情。

还有一些方法:.get_screenshot_as_base64()(用于嵌入 HTML)和.get_screenshot_as_png()(用于检索二进制数据)。

注意WebElements 有一个.screenshot() 方法,其工作方式类似,但只捕获选定的元素。

【讨论】:

  • 对于其他浏览器,交换webdriver实例。如果您只想要包括状态在内的网站截图,请查看Usersnap
  • @DavidRöthlisberger 很好,但您的评论与我的回答无关
  • 要制作整个页面的截图,而不仅仅是可见区域,请使用我在此处回答中的 python 代码来缝合:stackoverflow.com/questions/37906704/…
  • @CoreyGoldberg 没错,与您的回答无关。但是我的旧脚本使用了旧的 FF,它确实占用了整个页面,而不仅仅是视口。在他们将其更改为标准后,现在只有视口。所以我想帮助有同样问题的人。是的,固定元素是滚动/缝合的真正痛苦!
  • 另一件事对我帮助很大,如果您需要更改图像尺寸,只需在拍摄快照之前使用driver.set_window_size(1366, 728) 设置窗口大小。
【解决方案3】:

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

【讨论】:

  • 完美运行。警告:拍摄屏幕截图而不是页面截图。
  • 你的意思是它得到桌面和一切?或者你的意思是它只是获取视口?
  • 它只会获取驱动范围内的内容,这是为了允许进行多个并行测试。请注意,如果您的驱动程序的主窗口焦点有滚动条或超出单个页面,则它不会缩小。
  • 更新到 SaveAsFile(string path, ScreenshotImageFormat 格式) ScreenshotImageFormat.Jpeg
  • 这对我有用!我使用的是 Graphics 命名空间中的 CopyFromScreen。上述解决方案的优点是它在从 TFS 以无头方式调用代码时有效。我的旧 CopyFromScreen 方法仅在从 Visual Studio 运行 selenium 测试时有效,但对我的 TFS 运行测试无效。
【解决方案4】:

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

【讨论】:

  • 类似于 Browserstack 的描述:browserstack.com/automate/node#enhancements-screenshots
  • in data.replace 括号中你到底在做什么?
  • @JohnDemetriou,data 是您调用它时将创建的对象或变量的名称。如果你愿意,你可以叫它var1。你应该查看takeScreenshot() 函数以了解它到底是什么。也许是使用画布从 javascript 渲染的二进制图像。在渲染之前,它可以是 dom。调查一下。
【解决方案5】:

红宝石

require 'rubygems'
require 'selenium-webdriver'

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

更多文件类型和选项可用,您可以在文件 takes_screenshot.rb 中查看它们。

【讨论】:

  • 使用 Selenium Grid 2 对我来说效果很好。在 OS X Snow Leopard 上运行的脚本和集线器;在 Xvfb 下运行在 RedHat EL 4 和 Firefox 3.6.18 上的节点。
  • 有什么办法可以截取整页截图,而不仅仅是可见区域?
  • 默认采用整页。至少使用headlessFirefox
  • 为什么driver.save_screenshot 有括号,而driver.get 却没有?
  • @PeterMortensen - 不确定,自从我使用 Ruby 以来已经足够长了,我不记得两者之间是否有任何功能差异......我的直觉说它们是一样的......但我出于安全原因,建议使用完整的括号。
【解决方案6】:

Java

我已经解决了这个问题。您可以扩充 RemoteWebDriver 以向其提供其代理驱动程序实现的所有接口:

WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); // It works this way

【讨论】:

  • 如果您这样做,那么您是否不需要将屏幕截图复制到带有 threadId 的文件名,以便您可以判断驱动程序的哪些线程/实例抛出了屏幕截图?否则,一个网格节点上的多个浏览器实例会覆盖彼此的屏幕截图?
  • 我想指出,只有这个解决方案对我使用无头 ChromeDriver 有效
【解决方案7】:

PHP (PHPUnit)

它使用 PHPUnit_Selenium 扩展版本 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');
    }
    ...
}

【讨论】:

  • daaaamn!我想了解更多,Selenium 对我来说是新手,我正在寻找一个 cli 解决方案来创建跨多个浏览器和操作系统的屏幕截图以进行可视化测试
【解决方案8】:

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

【讨论】:

    【解决方案9】:

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

    【讨论】:

    • 你用的是什么驱动?新的 Augmenter().augment(driver);
    • 解释一下。您可以edit your answer没有“编辑:”、“更新:”或类似内容)。
    【解决方案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"))
    

    【讨论】:

      【解决方案11】:

      Java (Robot Framework)

      我就是用这个方法截图的。

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

      您可以在任何需要的地方使用此方法。

      【讨论】:

      • 您的焦点应该始终保持在浏览器上,否则会拍摄当前焦点的快照。
      【解决方案12】:

      Java

      这里似乎缺少 - 在 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);
      }
      

      【讨论】:

      • 我不认为这种方法实际可行,因为屏幕截图和实际浏览器具有不同的分辨率。因此,当在图像上使用 selenium 获得的坐标位置时,您肯定会遇到 java.awt.image.RasterFormatException: (y + height) is outside of Raster
      • 你试过代码了吗?当我上次尝试时,它起作用了。
      • 只要您尝试捕获不滚动即可看到的元素,它就可以正常工作。当您需要滚动到某个元素以捕获它时,y 偏移量从页面顶部开始计算,然后超出全屏图像的边界。所以最简单的解决方案是要么增加屏幕尺寸codethis.driver.manage().window().setSize(new Dimension(1680, 1050));或通过 css 删除任何不需要的元素。正确的解决方案是计算滚动的 y 偏移量。
      • In Firefox 工作正常,因为它根据尺寸从完整图像中裁剪元素屏幕。在 Chrome 中,如果元素在视图部分中可用,而无需从该视图部分滚动图像,它就会很好地捕获元素。如果我们想在滚动document.documentElement.clientHeight 两次客户端高度后截取屏幕截图,请使用(location.y)-2*clientHeight 获取准确的元素截图。感谢这篇文章,因为它对我有帮助...
      • 它对我不起作用。它不是截取特定元素的屏幕截图(它应该这样做),而是截取整个可见屏幕的屏幕截图。附言我正在使用 ChromeDriver 89。
      【解决方案13】:

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

      它需要 NuGet 包:

      1. PhantomJS 2.0.0
      2. Selenium.Support 2.48.2
      3. Selenium.WebDriver 2.48.2

      已使用 .NET Framework v4.5.2 测试。

      【讨论】:

        【解决方案14】:

        Java

        我无法得到公认的工作答案,但根据the current WebDriver documentation,以下对我来说在OS X v10.9(小牛队)上使用Java 7 效果很好:

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

        【讨论】:

          【解决方案15】:

          有多种方法可以通过SeleniumJavaPython客户端使用Selenium WebDriver进行截图


          Java 方法

          以下是获取屏幕截图的不同 Java 方法:

          • 使用来自TakesScreenshot 接口的getScreenshotAs()

          • 代码块:

                 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();
                     }
                 }
            
          • 截图:

          • 如果网页启用了jQuery,您可以使用pazone/ashot库中的

          • 代码块:

                 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();
                     }
                 }
            
          • 截图:

          • 使用来自assertthat/selenium-shutterbug 库的

          • 代码块:

                 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();
                     }
                 }
            
          • 截图:


          Python 方法

          以下是获取屏幕截图的不同 Python 方法:

          • 使用save_screenshot()方法:

          • 代码块:

                 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()
            
          • 截图:

          • 使用get_screenshot_as_file() 方法:

          • 代码块:

                 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()
            
          • 截图:

          • 使用get_screenshot_as_png()方法:

          • 代码块:

                 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()
            
          • 截图:

          【讨论】:

            【解决方案16】:

            红宝石(黄瓜)

            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
            

            【讨论】:

            • 这是什么语言?
            • 这看起来像是在 ruby​​ 中,没有使用任何特定的网络驱动程序
            【解决方案17】:

            红宝石

            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
            

            【讨论】:

              【解决方案18】:

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

              【讨论】:

              • 在当前版本的 facebook/webdriver 方法是 takeScreenshot() 并且在保存文件之前不需要 base64_encode() 输出。
              • 能否在您的示例中添加代码以显示如何调用此takescreenshot 函数?具体来说,$event 变量来自哪里?我是一个完整的 Selenium 菜鸟,因此非常感谢您回答这个不假设之前的 Selenium 知识的问题!
              【解决方案19】:

              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
              

              【讨论】:

              • 使用[OpenQA.Selenium.ScreenshotImageFormat]::Png 可能比使用System.Drawing 命名空间更好。
              【解决方案20】:

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

              【讨论】:

                【解决方案21】:

                Java

                使用RemoteWebDriver,在节点增加截图功能后,我会像这样存储截图:

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

                您可以在需要时使用此方法。然后,我假设您可以在 surefire-reports/html/custom.css 自定义 maven-surefire-report-plugin 的样式表,以便您的报告包含指向每个测试的正确屏幕截图的链接?

                【讨论】:

                • 现在我不会这样做。我可能会使用像 Selenide 这样的框架。
                【解决方案22】:

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

                【讨论】:

                  【解决方案23】:

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

                  使用这两种方法,您还可以截取带有日期和时间的屏幕截图。

                  【讨论】:

                    【解决方案24】:

                    Selenese

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

                    【讨论】:

                      【解决方案25】:

                      Python

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

                      它将屏幕截图保存在保存脚本的同一目录中。

                      【讨论】:

                      • 这个答案是在原始 Python 答案几年后发布的副本。
                      【解决方案26】:

                      你可以试试AShot API。是on GitHub

                      Examples of tests.

                      【讨论】:

                        【解决方案27】:

                        C#

                        您可以使用以下代码 sn-p/function 使用 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);
                            }
                        

                        【讨论】:

                        • "使用 System.Drawing.Imaging;"大会。
                        • 我不得不在 SaveAsFile 调用中使用这一行: ss.SaveAsFile(filename, ScreenshotImageFormat.Png);我也更喜欢在路径 + @"\" 上使用 Path.Combine(folder, filename),因为它读起来更好,而且我认为它可能对文件夹/文件名格式设置.variations 更宽容。仅个人喜好。因此该行变为:filename = Path.Combine(path, filename + ".png");
                        【解决方案28】:

                        Java

                        一种用于捕获 Selenium 中失败的屏幕截图的方法,并附加了 TestName 和 Timestamp。

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

                        【讨论】:

                        • 如果您发现这个(或任何)答案有帮助,请点赞。如果这回答了您的问题,请将其标记为已接受的答案。谢谢!
                        【解决方案29】:

                        C#(Ranorex API)

                        public static void ClickButton()
                        {
                            try
                            {
                                // code
                            }
                            catch (Exception e)
                            {
                                TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
                                Report.Screenshot();
                                throw (e);
                            }
                        }
                        

                        【讨论】:

                        【解决方案30】:

                        您可以使用Webdriverclass 对象创建一个webdriverbacked selenium object,然后您可以截图。

                        【讨论】:

                          猜你喜欢
                          • 2014-04-28
                          • 1970-01-01
                          • 1970-01-01
                          • 2019-03-11
                          • 1970-01-01
                          • 2018-05-21
                          • 2012-10-26
                          • 2023-01-23
                          相关资源
                          最近更新 更多