How can I take a screenshot with Selenium WebDriver?

后端 未结 30 2576
不知归路
不知归路 2020-11-21 07:48

Is it possible to take a screenshot using Selenium WebDriver?

(Note: Not Selenium Remote Control)

相关标签:
30条回答
  • 2020-11-21 08:26

    Ruby

    time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M_%S')
    file_path = File.expand_path(File.dirname(__FILE__) + 'screens_shot')+'/'+time +'.png'
    #driver.save_screenshot(file_path)
    page.driver.browser.save_screenshot file_path
    
    0 讨论(0)
  • 2020-11-21 08:27

    Ruby (Cucumber)

    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 讨论(0)
  • 2020-11-21 08:28

    There are multiple methods through Selenium's Java and Python client to take a screenshot using Selenium WebDriver.


    Java Methods

    The following are the different Java methods to take a screenshot:

    • Using getScreenshotAs() from the TakesScreenshot interface:

    • Code block:

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

      Mads_Cruz_screenshot

    • If the webpage is jQuery enabled, you can use ashot from the pazone/ashot library:

    • Code block:

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

      firefoxScreenshot.png

    • Using selenium-shutterbug from assertthat/selenium-shutterbug library:

    • Code block:

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

      2019_03_12_16_30_35_787.png


    Python Methods

    The following are the different Python methods to take a screenshot:

    • Using save_screenshot() method:

    • Code block:

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

      save_screenshot_method.png

    • Using the get_screenshot_as_file() method:

    • Code block:

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

      get_screenshot_as_file_method.png

    • Using get_screenshot_as_png() method:

    • Code block:

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

      get_screenshot_as_png_method.png

    0 讨论(0)
  • 2020-11-21 08:28

    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 讨论(0)
  • 2020-11-21 08:29

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

    It requires NuGet packages:

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

    It was Tested with .NET Framework v4.5.2.

    0 讨论(0)
  • 2020-11-21 08:31

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题