Best way to take screenshot of a web page Best way to take screenshot of a web page selenium selenium

Best way to take screenshot of a web page


I'd recommend getScreenshotAs. It gets even the 'out of view' part of the screen.

Here is some sample code in gr0ovy.

import java.io.IOExceptionimport java.net.URLimport java.nio.file.Pathimport java.nio.file.Pathsimport java.text.SimpleDateFormatimport org.openqa.selenium.Capabilitiesimport org.openqa.selenium.TakesScreenshotimport org.openqa.selenium.WebDriverExceptionimport org.openqa.selenium.remote.CapabilityTypeimport org.openqa.selenium.remote.DriverCommandimport org.openqa.selenium.remote.RemoteWebDriverimport org.openqa.selenium.OutputTypeimport org.openqa.selenium.WebDriverpublic class Selenium2Screenshot {private WebDriver driverprivate String browserTypeprivate boolean skipScreenshotspublic Selenium2Screenshot(WebDriver webDriver, String browserType, boolean skipScreenshots) {    this.driver = webDriver    this.browserType = browserType    this.skipScreenshots = skipScreenshots}public void takeScreenshot(String filenameBase) {    if (!skipScreenshots) {        Date today        String formattedDate        SimpleDateFormat formatter        Locale currentLocale        File scrFile        currentLocale = new Locale("en", "US")        formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS", currentLocale)        today = new Date()        formattedDate = formatter.format(today)        String filename = getUiAutomationDir() + filenameBase + "_" + browserType + formattedDate + ".png"        Log.logger.info("Screenshot filename = " + filename)        try {            scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)            JavaIO.copy(scrFile.getAbsolutePath(), filename)        } catch (Exception e) {            Log.logger.error(e.message, e)        }    } else {        Log.logger.info("Skipped Screenshot")    }}private String getUiAutomationDir(){    String workingDir = System.getProperty("user.dir")    Path workingDirPath = Paths.get(workingDir)    String returnString = workingDirPath.toString() + "\\"    return returnString}

}

Edited on 8/1/12:

Get application handle code. I am surely duplicating code that is on stackoverflow several times, but hopefully this is not the exact same code as in other posts :-)

public static IntPtr FindWindowByPartialCaption(String partialCaption)    {        var desktop = User32.GetDesktopWindow();        var children = EnumerateWindows.GetChildWindows(desktop);        foreach (var intPtr in children)        {            var current = GetText(intPtr);            if (current.Contains(partialCaption))                return intPtr;        }        return IntPtr.Zero;    }    [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]    public static extern IntPtr GetDesktopWindow();    [DllImport("user32.dll")]    public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowProc lpEnumFunc, IntPtr lParam);    public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);    public static List<IntPtr> GetChildWindows(IntPtr parent)    {        return GetChildWindows(parent, false);    }    public static List<IntPtr> GetChildWindows(IntPtr parent, bool reverse)    {        List<IntPtr> result = new List<IntPtr>();        GCHandle listHandle = GCHandle.Alloc(result);        try        {            EnumWindowProc childProc = new EnumWindowProc(EnumWindow);            EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));        }        finally        {            if (listHandle.IsAllocated)                listHandle.Free();        }        if (reverse)        {            List<IntPtr> resultList = result.Reverse<IntPtr>().ToList();            return resultList;        }         else            return result;    }    private static bool EnumWindow(IntPtr handle, IntPtr pointer)    {        GCHandle gch = GCHandle.FromIntPtr(pointer);        List<IntPtr> list = gch.Target as List<IntPtr>;        if (list == null)        {            throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");        }        list.Add(handle);        //  You can modify this to check to see if you want to cancel the operation, then return a null here        return true;    }}

http://www.pinvoke.net/ is also a great resource.


http://msdn.microsoft.com/en-us/library/windows/desktop/dd162869(v=vs.85).aspx

I personally love this API. Create a bitmap with width and height calculated from the returned rectangle of GetWindowRect API and for HDC parameter use (for example):

thebitmap.GetHdc()

You should be fine.

Edit: also check this.

Btw, you can take screenshot of any window you like, even if they fall back.(note that this will not work for minimized windows. However, if you really need, there are some way arounds for that too.)


If you're looking for a programmatic way to get a screenshot of the main window of a given process, here is a function that does it:

    public static Bitmap TakeScreenshot(Process process)    {        // may need a process Refresh before        return TakeScreenshot(process.MainWindowHandle);    }    public static Bitmap TakeScreenshot(IntPtr handle)    {        RECT rc = new RECT();        GetWindowRect(handle, ref rc);        Bitmap bitmap = new Bitmap(rc.right - rc.left, rc.bottom - rc.top);        using (Graphics graphics = Graphics.FromImage(bitmap))        {            PrintWindow(handle, graphics.GetHdc(), 0);        }        return bitmap;    }    [DllImport("user32.dll")]    private static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);    [DllImport("user32.dll")]    private static extern bool PrintWindow(IntPtr hWnd, IntPtr hDC, int flags);    [StructLayout(LayoutKind.Sequential)]    private struct RECT    {        public int left;        public int top;        public int right;        public int bottom;    }

Unfortunately, on Aero-equipped OS (Vista/Win7/Win8) it will not capture the full transparent border. The usual transparent border will be blacked instead. Maybe it's enough for what you're trying to acomplish.