525

是否可以使用 Selenium WebDriver 截屏?

(注意:不是Selenium 遥控器

4

47 回答 47

530

爪哇

是的,有可能。以下示例使用 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"));
于 2010-08-06T11:33:22.940 回答
296

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()方法,但只捕获选定的元素。

于 2011-06-08T16:37:56.560 回答
114

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;
    }
}
于 2013-09-06T15:02:24.563 回答
81

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);
   });
});
于 2013-06-02T11:13:45.040 回答
68

红宝石

require 'rubygems'
require 'selenium-webdriver'

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

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

于 2011-08-18T20:03:25.193 回答
35

爪哇

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

WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); // It works this way
于 2011-09-03T18:08:16.580 回答
34

PHP ( PHP单元)

它使用 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');
    }
    ...
}
于 2012-06-22T17:38:39.613 回答
29

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);
}
于 2013-01-12T16:16:08.880 回答
19

爪哇

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;
}
于 2012-05-09T03:05:30.473 回答
13

杰通

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"))
于 2012-05-07T10:14:22.793 回答
11

Java(机器人框架

我用这种方法截屏。

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

您可以在需要时使用此方法。

于 2012-03-20T08:48:04.667 回答
9

爪哇

这里似乎缺少 - 截取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);
}
于 2014-01-27T09:07:42.957 回答
6

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. 幻影JS 2.0.0
  2. Selenium. 支持 2.48.2
  3. Selenium.WebDriver 2.48.2

它使用 .NET Framework v4.5.2 进行了测试。

于 2016-06-03T04:03:43.433 回答
4

爪哇

我无法获得公认的工作答案,但根据当前的 WebDriver 文档,以下对我来说在OS X v10.9 (Mavericks) 上使用 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);
   }
}
于 2014-02-23T06:12:46.117 回答
4

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


Java 方法

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

  • getScreenshotAs()TakesScreenshot界面使用:

  • 代码块:

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

    Mads_Cruz_screenshot

  • 如果网页启用了jQuery,您可以使用pazone ashot库中的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();
             }
         }
    
  • 截屏:

    firefox截图.png

  • 使用assertthat/selenium shutterbug库中的 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();
             }
         }
    
  • 截屏:

    2019_03_12_16_30_35_787.png


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

    save_screenshot_method.png

  • 使用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_file_method.png

  • 使用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()
    
  • 截屏:

    get_screenshot_as_png_method.png

于 2019-03-12T11:10:41.897 回答
3

红宝石(黄瓜)

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
于 2012-12-18T07:14:54.383 回答
3

红宝石

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
于 2013-01-22T08:31:41.097 回答
3

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));
    }
  }
于 2013-09-11T13:31:56.633 回答
3

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);
}
于 2014-08-26T11:09:56.673 回答
3

电源外壳

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
于 2015-03-10T10:41:21.047 回答
2

爪哇

使用 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 的样式表,以便您的报告包含指向每个测试的正确屏幕截图的链接?

于 2013-09-06T17:51:00.420 回答
2

爪哇

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));
于 2014-04-15T11:04:38.770 回答
2

爪哇

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

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

于 2014-05-06T04:31:42.153 回答
2

塞勒内斯

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
于 2014-06-20T08:07:00.863 回答
2

Python

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

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

于 2014-06-27T06:21:21.547 回答
2

你可以试试AShot API。它在 GitHub 上

测试示例

于 2016-04-18T16:32:43.293 回答
2

C#

您可以使用以下代码片段/函数使用 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);
    }
于 2016-11-16T13:16:29.687 回答
2

爪哇

一种捕获 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();
      }
   }
于 2017-03-23T10:27:46.567 回答
1

webdriverbacked selenium object您可以使用类对象创建一个Webdriver,然后您可以截屏。

于 2011-12-11T06:46:24.710 回答
1

Python

您可以使用 Python Web 驱动程序从 Windows 捕获图像。使用下面的代码需要捕获屏幕截图的页面。

driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')
于 2012-12-13T09:39:55.070 回答
1

C# (Ranorex API)

public static void ClickButton()
{
    try
    {
        // code
    }
    catch (Exception e)
    {
        TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
        Report.Screenshot();
        throw (e);
    }
}
于 2014-05-28T15:56:20.803 回答
1

爪哇

我想我会给出完整的解决方案,因为有两种不同的方式来获取屏幕截图。一种来自本地浏览器,一种来自远程浏览器。我什至将图像嵌入到 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 a screenshot from the remote driver
                Augmenter augmenter = new Augmenter();
                TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver);
                screenshot = ts.getScreenshotAs(OutputType.BYTES);
            } 
            else { // Get a screenshot from the local driver
                // Local webdriver user flow
                screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            }
            scenario.embed(screenshot, "image/png"); // Embed the image in reports
        } 
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } 
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }

    //seleniumCleanup();
}
于 2014-10-06T17:33:32.957 回答
1

硒化物/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})
于 2015-11-16T21:01:32.633 回答
1

机器人框架

这是使用带有Selenium2Library的 Robot Framework 的解决方案:

*** Settings ***
Library                        Selenium2Library

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

这将在工作空间中保存屏幕截图。也可以为关键字提供文件名以Capture Page Screenshot更改该行为。

于 2016-07-19T08:34:55.010 回答
1

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"));
于 2017-04-12T17:38:52.730 回答
1

是的,可以使用 Selenium WebDriver 拍摄网页的快照。

getScreenshotAs()WebDriver API 提供的方法为我们完成了工作。

句法: getScreenshotAs(OutputType<X> target)

返回类型: X

参数: target – 检查提供的选项OutputType

适用性:不特定于任何 DOM 元素

例子:

TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);

有关更多详细信息,请参阅下面的工作代码片段。

public class TakeScreenShotDemo {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get(“http: //www.google.com”);

        TakesScreenshot screenshot = (TakesScreenshot) driver;

        File file = screenshot.getScreenshotAs(OutputType.FILE);

        // Creating a destination file
        File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
        try {
            FileUtils.copyFile(file, destination);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

访问使用 WebDriver 的快照以获取更多详细信息。

于 2017-09-17T18:22:35.400 回答
0

我在 C# 中使用以下代码获取整个页面或仅获取浏览器屏幕截图

public void screenShot(string tcName)
{
    try
    {
        string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
        string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
        ITakesScreenshot screen = driverScript.driver as ITakesScreenshot;
        Screenshot screenshot = screen.GetScreenshot();
        screenshot.SaveAsFile(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
        if (driverScript.last == 1)
            this.writeResult("Sheet1", "Fail see Exception", "Status", driverScript.resultRowID);
    }
    catch (Exception ex)
    {
        driverScript.writeLog.writeLogToFile(ex.ToString(), "inside screenShot");
    }
}

public void fullPageScreenShot(string tcName)
{
    try
    {
        string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
        string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
        Rectangle bounds = Screen.GetBounds(Point.Empty);
        using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
            }
            bitmap.Save(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
        }
        if (driverScript.last == 1)
            this.writeResult("Sheet1", "Pass", "Status", driverScript.resultRowID);
    }
    catch (Exception ex)
    {
        driverScript.writeLog.writeLogToFile(ex.ToString(), "inside fullPageScreenShot");
    }
}
于 2015-12-01T08:38:36.577 回答
0
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage originalImage = ImageIO.read(scrFile);
//int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
于 2017-02-14T09:12:56.723 回答
0
public static void getSnapShot(WebDriver driver, String event) {

    try {
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        BufferedImage originalImage = ImageIO.read(scrFile);
        //int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
        ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
        Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
        jpeg.setAlignment(Image.MIDDLE);
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell1 = new PdfPCell(new Paragraph("\n"+event+"\n"));
        PdfPCell cell2 = new PdfPCell(jpeg, false);
        table.addCell(cell1);
        table.addCell(cell2);
        document.add(table);
        document.add(new Phrase("\n\n"));
        //document.add(new Phrase("\n\n" + event + "\n\n"));
        //document.add(jpeg);
        fileWriter.write("<pre>        " + event + "</pre><br>");
        fileWriter.write("<pre>        " + Calendar.getInstance().getTime() + "</pre><br><br>");
        fileWriter.write("<img src=\".\\img\\" + index + ".jpg\" height=\"460\" width=\"300\"  align=\"middle\"><br><hr><br>");
        ++index;
    }
    catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
}
于 2017-02-15T03:36:22.250 回答
0

Python

webdriver.get_screenshot_as_file(filepath)

上述方法将截取屏幕截图并将其作为文件存储在作为参数提供的位置中。

于 2018-06-11T09:47:45.070 回答
0

是的,可以通过Selenium WebDriver截屏。我目前Chrome Driver用于捕捉网站的图像。请参考以下方法captureScreenshot()

您还可以添加对 Web 驱动程序的限制,例如

  • 使用无头版本的网络浏览器
  • 页面加载时禁用通知
  • 启动全屏等

如果网站配备了警报框,您的网络驱动程序将无法捕获屏幕截图,因为会引发异常。在这种情况下,您需要关闭警报框,然后获取屏幕截图。以下代码片段关闭警报框。

    public void captureScreenshot() throws InterruptedException, IOException {

        System.out.println("Creating Chrome Driver");

        // Set Chrome Driver
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");

        // Add arguments to Chrome Options
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("start-maximized");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--start-fullscreen");
        chromeOptions.addArguments("--disable-extensions");
        chromeOptions.addArguments("--disable-popup-blocking");
        chromeOptions.addArguments("--disable-notifications");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--dns-prefetch-disable");
        chromeOptions.addArguments("enable-automation");
        chromeOptions.addArguments("disable-features=NetworkService");

        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get("https://www.google.com");
        System.out.println("Wait a bit for the page to render");
        TimeUnit.SECONDS.sleep(5);
        System.out.println("Taking Screenshot");
        File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        String imageDetails = "D:\\Images";
        File screenShot = new File(imageDetails).getAbsoluteFile();
        FileUtils.copyFile(outputFile, screenShot);
        System.out.println("Screenshot saved: {}" + imageDetails);
    }
}

为了接受警报框并获取屏幕截图:

String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "D://Images"
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
driver.close();
于 2019-11-04T06:42:13.303 回答
0

爪哇

对于较新版本的 Java,FileUtils函数不起作用。以下功能非常适合屏幕截图复制。

import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.io.FileHandler;

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File destfile = new File(destination folder /filename.extension);
FileHandler.copy(scrfile, destfile);
于 2020-02-28T12:07:15.880 回答
0
/**
 * Take a screenshot and move to the given folder location.
 *
 * @param driver
 * @param folderLocation
 * @return screenShotFilePath
 */
public static String captureScreenshot(WebDriver driver, String folderLocation) {

    // Variable to store screenshot's file path.
    String screenShotFilePath = null;

    // Generate unique id for screen shot name.
    String uniqueId = UUID.randomUUID().toString().substring(31);

    if (driver != null) {

        // Generate screenshot as a file
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // New screenshot file path with having file name
        screenShotFilePath = folderLocation + File.separator + uniqueId + ".png";

        // Move file to the destination location.
        FileUtils.moveFile(scrFile, new File(screenShotFilePath));
    }

    return screenShotFilePath;
}
于 2020-05-13T21:03:55.510 回答
0

使用 C# 和 MSTestframework,我在这里创建了一个静态方法。采取了一条路径,我可以将图像存储为 jpeg 格式。为了更清楚,我用当前执行的测试用例以及失败的日期和时间来命名这些屏幕截图。

          /// <summary>
            /// This method is used to screen shot where test method failed 
            /// </summary>
            /// <param name="testCase">TestCaseName</param>
            public static void Capture(string testCase)
            {
                try
                {
                    StringBuilder path = new StringBuilder("C:/Logs/Screenshot/");
                    Constant.screenshot = ((ITakesScreenshot)Constant.browser).GetScreenshot();
                    string fileName = path.Append(string.Format(testCase + "-at-{0:yyyy-MM dd_hh-mm-ss}.jpeg", DateTime.Now)).ToString();
                    Constant.screenshot.SaveAsFile(fileName, ScreenshotImageFormat.Jpeg);
                }
                catch (Exception e)
                {
                    File.AppendAllText("C:/Logs/FailedTestCasesLogs.txt", "\nCOULD NOT CAPTURE THE SCREENSHOT!\n");
                    Log(e);
                }
    
            }
于 2021-04-17T13:08:28.377 回答
0

您可以在浏览器中截取网页可见部分的屏幕截图:

第一次导入:

import java.io.File;
import com.google.common.io.Files;

然后

File src=((TakesScreenshot)driver).getScreenShotAs(OutputType.FILE);
Files.copy(src,new File("new path/pic.jpeg"));

另外在 Selenium4 之后,您还可以将 webelement 的屏幕截图如下:

WebElement element=driver.findElement(By.xpath("xpath 
 here"));
File src=element.getScreenShotAs(OutputType.FILE);
File.copy(src,new File("new path/pic.jpeg"));
于 2022-01-10T19:01:14.650 回答
0

JAVA

嗨,您可以在 selenium 中截屏,这是下面给出的代码,您可以借助它在任何 selenium 项目中创建屏幕截图,我们也可以在 aws 中为失败的场景生成屏幕截图。

    public boolean takeScreenshot(final String name) {
    String screenshotDirectory = System.getenv("WORKING_DIRECTORY");
    File screenshot = 
    ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    return screenshot.renameTo(new File(screenshotDirectory, 
    String.format("%s.png", name)));
    }
于 2022-01-17T21:36:44.847 回答
-1
import java.io.File;
import java.io.IOException;

import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
 * @author Jagdeep Jain
 *
 */
public class ScreenShotMaker {

    // take screen shot on the test failures
    public void takeScreenShot(WebDriver driver, String fileName) {
        File screenShot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));

        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        }
    }

}
于 2016-01-29T07:06:55.197 回答