使用Selenium WebDriver截取屏幕截图

Jam*_*rth 478 selenium selenium-webdriver ashot takesscreenshot selenium-shutterbug

有谁知道是否可以使用Selenium WebDriver截取屏幕截图?(注:不是Selenium RC)

Ser*_*rov 486

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"));
Run Code Online (Sandbox Code Playgroud)

  • 如果源和目标可能不在同一文件系统上,则复制文件而不是重命名是个好主意.您不能跨文件系统边界重命名(至少在unix上).请注意,`/ tmp`通常位于自己的文件系统上,FirefoxDriver将屏幕截图写入`/ tmp`. (30认同)
  • 有没有办法只为失败的案件做到这一点? (9认同)
  • @RiponAlWasim可能是`org.apache.commons.io.FileUtils` (7认同)
  • 值得注意的是,`HtmlUnitDriver`没有实现`TakesScreenshot`(请参阅http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/TakesScreenshot.html获取支持的驱动程序列表) .但您可以另存为HTML. (6认同)
  • 使用FileUtils类导入需要什么包? (5认同)

Cor*_*erg 257

蟒蛇

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

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')
Run Code Online (Sandbox Code Playgroud)

令人困惑的是,.get_screenshot_as_file(filename)也存在同样的方法.

还有以下方法:( .get_screenshot_as_base64()用于嵌入html)和.get_screenshot_as_png()(用于检索二进制数据).

并注意WebElements有一个.screenshot()类似的方法,但只捕获所选元素.

  • 不幸的是,这似乎不适用于网格系统. (2认同)
  • @CoreyGoldberg 是的,与你的答案无关。但我的旧脚本使用了旧的 FF,它确实占用了整个页面,而不仅仅是视口。在他们将其更改为标准后,现在只有视口。所以我想帮助有同样问题的人。是的,固定元素在滚动/缝合中是一个真正的痛苦! (2认同)
  • 还有一件对我有很大帮助的事情,如果您需要更改图像尺寸,只需在使用 `driver.set_window_size(1366, 728)` 拍摄快照之前设置窗口大小。 (2认同)

jes*_*ica 106

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 完美的工作.警告:拍摄一个屏幕截图不是一个页面. (9认同)
  • 更新到SaveAsFile(字符串路径,ScreenshotImageFormat格式)ScreenshotImageFormat.Jpeg (3认同)

Moi*_*aja 69

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);
   });
});
Run Code Online (Sandbox Code Playgroud)

  • 与Browserstack描述的类似:http://www.browserstack.com/automate/node#enhancements-screenshots (3认同)
  • 我用这个函数创建了一个函数:https://gist.github.com/mnbayazit/6441147 (2认同)

sir*_*sam 65

红宝石

require 'rubygems'
require 'selenium-webdriver'

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

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

  • 有没有办法截取整个页面的屏幕截图,而不仅仅是可见区域? (2认同)
  • 默认情况下采用整页.至少使用`headless`和`Firefox` (2认同)

use*_*910 35

Java的

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

WebDriver augmentedDriver = new Augmenter().augment(driver); 
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); //works this way
Run Code Online (Sandbox Code Playgroud)


Rya*_*ell 34

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');
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)


小智 24

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);
}
Run Code Online (Sandbox Code Playgroud)


小智 18

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;
}
Run Code Online (Sandbox Code Playgroud)


小智 12

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"))
Run Code Online (Sandbox Code Playgroud)


小智 9

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在需要的地方使用此方法.


Erk*_* M. 8

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);
}
Run Code Online (Sandbox Code Playgroud)


use*_*ond 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

需要NuGetPackages:

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

使用.NETFramework v4.5.2进行测试


Ste*_*HHH 5

Java的

我无法得到已接受的工作答案,但根据当前的WebDriver文档,在OS X 10.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);
   }
}
Run Code Online (Sandbox Code Playgroud)


Tec*_*pud 5

电源外壳

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)
Run Code Online (Sandbox Code Playgroud)

其他司机...

$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
Run Code Online (Sandbox Code Playgroud)


Deb*_*anB 5

有多种方法可以通过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();
             }
         }
    
    Run Code Online (Sandbox Code Playgroud)
  • 截屏:

    Mads_Cruz_截图

  • 如果网页启用了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();
             }
         }
    
    Run Code Online (Sandbox Code Playgroud)
  • 截屏:

    firefox屏幕截图.png

  • 使用来自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();
             }
         }
    
    Run Code Online (Sandbox Code Playgroud)
  • 截屏:

    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()
    
    Run Code Online (Sandbox Code Playgroud)
  • 截屏:

    保存屏幕截图方法.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()
    
    Run Code Online (Sandbox Code Playgroud)
  • 截屏:

    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()
    
    Run Code Online (Sandbox Code Playgroud)
  • 截屏:

    get_screenshot_as_png_method.png


归档时间:

查看次数:

516710 次

最近记录:

6 年 前