如何使用 Selenium WebDriver 截屏?

How to take a screenshot with Selenium WebDriver?

提问人:James Hollingworth 提问时间:8/6/2010 最后编辑:Super Kai - Kazuya ItoJames Hollingworth 更新时间:9/15/2023 访问量:657780

问:

是否可以使用 Selenium WebDriver 截屏?

(注意:不是 Selenium 遥控器)

selenium-webdriver 截图 ashot selenium-shutterbug

评论

0赞 oberlies 5/16/2014
使用 WebDriver Wire 协议可能只有一种方法可以做到这一点,但没有人直接使用此协议。相反,人们使用不同的语言绑定/库来包装低级协议。有大量的语言绑定,所以你需要说出你想使用哪一个。否则,答案太多了。
3赞 Ripon Al Wasim 4/12/2016
您使用的是哪种编程语言?
0赞 Ripon Al Wasim 4/12/2016
您想截取整个页面或特定元素的屏幕截图吗?
0赞 Ripon Al Wasim 11/16/2016
是的,可以使用 Selenium WebDriver 截取整个页面或特定元素的屏幕截图

答:

553赞 Sergii Pozharov 8/6/2010 #1

爪哇岛

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

评论

34赞 Tom Anderson 12/16/2011
如果源文件和目标可能不在同一文件系统上,则复制文件(而不是重命名文件)是一个好主意。您不能跨文件系统边界重命名(至少在 unix 上是这样)。请注意,它通常位于自己的文件系统上,FirefoxDriver 会将屏幕截图写入 ./tmp/tmp
9赞 some_other_guy 8/23/2012
有没有办法只对失败的情况这样做?
6赞 Wernight 7/12/2013
值得注意的是,它没有实现(有关支持的驱动程序列表,请参阅 selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/...)。但您可以另存为 HTML。HtmlUnitDriverTakesScreenshot
10赞 Ripon Al Wasim 4/10/2014
使用 FileUtils 类需要导入什么包?
11赞 Ben 7/31/2014
@RiponAlWasim可能org.apache.commons.io.FileUtils
322赞 Corey Goldberg 6/9/2011 #2

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

from selenium import webdriver

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

令人困惑的是,还存在一种执行相同操作的方法。.get_screenshot_as_file(filename)

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

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

评论

0赞 Gregor 8/22/2013
对于其他浏览器,请交换 webdriver 实例。如果您只想要包括状态在内的网站屏幕截图,请查看 Usersnap
0赞 Corey Goldberg 2/27/2017
@DavidRöthlisberger这一切都很好,但你的评论与我的回答无关
0赞 Martin Krung 3/2/2017
要制作整个页面的 scrennshot,而不仅仅是可见区域,请使用我在这里的答案中的 python 代码来 stich:stackoverflow.com/questions/37906704/......
2赞 Martin Krung 11/28/2017
@CoreyGoldberg 没错,与你的答案无关。但是我的旧脚本使用了较旧的 FF,它确实占用了整个页面,而不仅仅是视口。在他们将其更改为标准之后,现在只有视口。所以我想帮助那些有同样问题的人。是的,固定元素是滚动/标记的真正痛苦!
3赞 srdg 6/6/2019
还有一件事对我有很大帮助,如果您需要更改图像尺寸,只需在使用 .driver.set_window_size(1366, 728)
71赞 sirclesam 8/19/2011 #3

红宝石

require 'rubygems'
require 'selenium-webdriver'

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

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

评论

0赞 MarkD 12/7/2011
使用 Selenium Grid 2 对我来说效果很好。在 OS X Snow Leopard 上运行的脚本和集线器;节点在 RedHat EL 4 上运行,在 Xvfb 下使用 Firefox 3.6.18。
2赞 Arihant Godha 8/28/2014
有没有办法截取整页截图,而不仅仅是可见区域?
2赞 Ashley 2/17/2015
默认情况下,将采用整页。至少使用 和headlessFirefox
0赞 Peter Mortensen 11/6/2020
为什么括号为 ,而不是 ?driver.save_screenshotdriver.get
0赞 sirclesam 12/16/2020
@PeterMortensen - 不确定,自从我使用 Ruby 以来已经足够长了,我不记得两者之间是否有任何功能差异......我的直觉说他们也是一样的......但出于安全原因,我建议完全使用。
38赞 user708910 9/4/2011 #4

爪哇岛

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

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

评论

0赞 djangofan 9/7/2013
如果这样做,那么是否不需要将屏幕截图复制到带有 threadId 的文件名中,以便您可以知道驱动程序的哪些线程/实例抛出了屏幕截图?否则,一个网格节点上的多个浏览器实例会相互覆盖屏幕截图?
1赞 rado 10/10/2018
我想指出的是,只有这个解决方案对我有用,使用无头 ChromeDriver
12赞 ank 3/20/2012 #5

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

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

评论

0赞 Kushal Bhalaik 5/11/2017
您的注意力应始终保持在浏览器上,否则会拍摄当前焦点的快照。
13赞 Fresh Mind 5/7/2012 #6

吉顿

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"))
19赞 SilverColt 5/9/2012 #7

爪哇岛

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

评论

0赞 kozla13 6/29/2017
你用的是什么驱动程序?新的 Augmenter().augment(驱动程序);
0赞 Peter Mortensen 11/6/2020
解释是有道理的。您可以编辑您的答案不带“编辑:”、“更新:”或类似内容)。
34赞 Ryan Mitchell 6/23/2012 #8

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

评论

0赞 pythonian29033 7/7/2016
哎呀!我想了解更多,Selenium 对我来说是新的,我正在寻找一种 cli 解决方案来跨多个浏览器和操作系统创建屏幕截图以进行视觉测试
3赞 vijay chouhan 12/18/2012 #9

红宝石(黄瓜)

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

评论

0赞 codygman 9/19/2013
这是什么语言?
0赞 James 5/10/2014
这看起来像是红宝石,没有使用任何特定的 Web 驱动程序
31赞 wsbaser 1/13/2013 #10

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);
}
3赞 vijay chouhan 1/22/2013 #11

红宝石

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
86赞 Moiz Raja 6/2/2013 #12

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

评论

3赞 Mike Causer 12/24/2013
类似于 Browserstack 的描述: browserstack.com/automate/node#enhancements-screenshots
0赞 John Demetriou 4/6/2015
在 data.replace 中,括号中您到底在做什么?
0赞 m3nda 6/10/2016
@JohnDemetriou,data 是调用对象或变量时将创建的对象或变量的名称。如果你愿意,你可以打电话给它。你应该看看函数就知道它到底是什么。也许是使用 canvas 从 javascript 渲染的二进制图像。在呈现之前,它可以是 dom。查。var1takeScreenshot()
119赞 jessica 9/6/2013 #13

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

评论

10赞 ljgww 4/23/2015
完美工作。注意:拍摄屏幕截图而不是页面截图。
0赞 vtortola 3/1/2017
你的意思是它得到桌面和一切吗?或者你的意思是它只是得到视口?
0赞 Ben 3/29/2017
它只会获取驱动程序范围内的内容,这是为了允许进行多个并行测试。请注意,如果驱动程序的主窗口焦点有滚动条或超过单个页面,则不会缩小。
3赞 Kieran 8/1/2017
更新到 SaveAsFile(string path, ScreenshotImageFormat format) ScreenshotImageFormat.Jpeg
1赞 Ewan 10/12/2019
这对我有用!我正在使用 Graphics 命名空间中的 CopyFromScreen。上述解决方案的优点是,当从 TFS 以无头方式调用代码时,它有效。我的旧 CopyFromScreen 方法仅在从 Visual Studio 运行硒测试时有效,但从未适用于我的 TFS 运行测试。
2赞 djangofan 9/7/2013 #14

爪哇岛

使用 RemoteWebDriver,在使用屏幕截图功能增强 Node 后,我会像这样存储屏幕截图:

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

评论

0赞 djangofan 7/13/2016
现在我不会这样做了。我可能会使用像 Selenide 这样的框架。
3赞 Arpan Buch 9/11/2013 #15

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

评论

0赞 billrichards 2/26/2016
在当前版本的 facebook/webdriver 中,方法是 takeScreenshot(),在保存文件之前不需要base64_encode() 输出。
2赞 Kenny83 9/30/2018
您能否在示例中添加代码来演示如何调用此函数?具体来说,变量从何而来?我是一个彻头彻尾的硒菜鸟,所以对这个问题的回答不假设之前有硒知识将不胜感激!takescreenshot$event
10赞 Erki M. 1/27/2014 #16

爪哇岛

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

评论

0赞 Ichwardort 11/27/2015
我不认为这种方法实际上行得通,因为屏幕截图和实际浏览器的分辨率不同。因此,当在图像上使用 selenium 获取的坐标位置时,您肯定会遇到 java.awt.image.RasterFormatException:(y + height) 位于 Raster 之外
0赞 Erki M. 11/27/2015
你试过代码吗?当我上次尝试它时,它起作用了。
1赞 Ichwardort 11/27/2015
只要您尝试捕获无需滚动即可看到的元素,它就可以正常工作。当您需要滚动到某个元素以捕获它时,则从页面顶部计算 y 偏移量,然后超出全屏图像的边界。所以最简单的解决方案是增加屏幕尺寸 this.driver.manage().window().setSize(new Dimension(1680, 1050));或通过 CSS 删除任何不需要的元素。正确的解决方案是计算滚动的 y 偏移量。code
1赞 Yash 8/19/2016
Firefox中,它可以很好地工作,因为它可以根据尺寸从完整的图像中裁剪元素屏幕。在 Chrome 中,如果该元素在视图部分可用,而无需从该视图部分滚动图像,则可以很好地捕获元素。如果我们想在滚动两次客户端高度后截取屏幕截图,则可以使用以获取确切的元素屏幕截图。感谢您的这篇文章,因为它对我有帮助......document.documentElement.clientHeight(location.y)-2*clientHeight
0赞 Tech Expert Wizard 4/12/2021
它对我不起作用。它不是截取特定元素的屏幕截图(它应该这样做),而是截取整个可见屏幕的屏幕截图。P.S. 我正在使用 ChromeDriver 89。
4赞 Steve HHH 2/23/2014 #17

爪哇岛

我无法得到公认的答案,但根据当前的 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);
   }
}
2赞 Yerram Naveen 4/15/2014 #18

爪哇岛

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赞 Raghuveer 5/6/2014 #19

爪哇岛

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

使用这两种方法,您还可以使用日期和时间截屏。

1赞 Benny Meade 5/28/2014 #20

C# (Ranorex API)

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

评论

0赞 Peter Mortensen 11/20/2020
什么是“Ranorex”?Ranorex 工作室
2赞 Bernát 6/20/2014 #21

硒犍

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
2赞 Hemant 6/27/2014 #22

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

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

评论

4赞 Corey Goldberg 12/13/2016
这个答案是在原始 Python 答案几年后发布的重复答案。
4赞 dmeehan 8/26/2014 #23

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);
}
5赞 TechSpud 3/10/2015 #24

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

评论

0赞 Adarsha 5/23/2017
可能比命名空间更好用。[OpenQA.Selenium.ScreenshotImageFormat]::PngSystem.Drawing
2赞 Khaja Mohammed 4/19/2016 #25

您可以尝试 AShot API。它在 GitHub 上

测试示例

8赞 userlond 6/3/2016 #26

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 包:It requires NuGet packages:

  1. 幻影JS2.0.0
  2. Selenium.Support 2.48.2
  3. Selenium.Web驱动程序 2.48.2

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

2赞 Mohsin Awan 11/16/2016 #27

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

评论

0赞 ArNumb 1/23/2017
“using System.Drawing.Imaging;”程序集。
0赞 Developer63 6/27/2019
我不得不在 SaveAsFile 调用中使用此行:ss。SaveAsFile(文件名, ScreenshotImageFormat.Png);我也更喜欢在路径 + @“\” 上使用 Path.Combine(folder, filename),因为它读起来更好,而且我认为它可能对文件夹/文件名格式化更宽容。仅个人喜好。所以这一行变成了:文件名 = Path.Combine(路径,文件名 + “.png”);
2赞 Anuj Teotia 3/23/2017 #28

爪哇岛

一种捕获 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();
      }
   }
5赞 undetected Selenium 3/12/2019 #29

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

    Mads_Cruz_screenshot

  • 如果网页启用了 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();
             }
         }
    
  • 截图:

    firefoxScreenshot.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

2赞 pr96 12/15/2022 #30

更新时间:2022

为了在 Selenium 中截取屏幕截图,我们使用一个名为 的接口,它使 Selenium WebDriver 能够捕获屏幕截图并以不同的方式存储它。它有一个捕获屏幕截图并将其存储在指定位置的方法。TakesScreenshotgetScreenshotAs()

//Convert webdriver to TakeScreenshot
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

在上面的代码中,它将 WebDriver 对象(驱动程序)转换为 TakeScreenshot。并调用方法通过提供参数来创建图像文件getScreenshotAs()*OutputType.FILE.

我们可以使用 File 对象将图像复制到我们想要的位置,如下所示,使用 .FileUtils Class

FileUtils.copyFile(screenshotFile , new File("C:\\temp\\screenshot.png));

捕获整个页面

Selenium WebDriver 不提供捕获整个页面屏幕截图的固有功能。要捕获整页屏幕截图,我们必须使用名为 Ashot 的第三方库。它提供了对特定 WebElement 进行屏幕截图以及整页屏幕截图的功能。

捕获屏幕大小图像

Screenshot screenshot = new Ashot().takeScreenshot(driver);

截取整页截图

Screenshot s=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(s.getImage(),"PNG",new File("<< file path>>"));

在上面的代码中,1000 是以毫秒为单位的滚动时间。换句话说,这意味着程序将每 1000 毫秒滚动一次以截取屏幕截图。

捕获 elememnt

有两种方法可以在 Selenium 中捕获 Web 元素的屏幕截图。

  • 获取全屏图像,然后根据 Web 元素的尺寸裁剪图像。
  • 在 Web 元素上使用方法。(这仅在 selenium 版本 4.X 中可用)getScreenshotAs()