Jump to content

WebDriver Full Page Screenshot


Recommended Posts

The key for Chrome is to run WebDriver headless.  If anyone has suggestions to improve this or it is helpful to anyone, please feel free to comment.

#include "wd_core.au3"
#include "wd_helper.au3"
#include "wd_capabilities.au3"

Global $bHidden = True
Global $sCapabilities = SetupChrome($bHidden)
_WD_Startup()

Global $sSession = _WD_CreateSession($sCapabilities)
If @error = $_WD_ERROR_Success Then
    Global $sURL = 'https://autoitscript.com/forum'
    _WD_Navigate($sSession, $sURL)
    _WD_LoadWait($sSession)
    Global $sFile = 'screenshot.png'
    _FullscreenScreenshot($sSession, $sFile)
    ShellExecuteWait($sFile)
EndIf
_WD_DeleteSession($sSession)
_WD_Shutdown()

Func SetupChrome($bHeadless)
    _WD_Option('Driver', 'chromedriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\chrome.log"')
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'chrome')
    _WD_CapabilitiesAdd('w3c', True)
    _WD_CapabilitiesAdd('excludeSwitches', 'enable-automation')
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupChrome

Func SetupEdge($bHeadless)
    _WD_Option('Driver', 'msedgedriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\msedge.log"')
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'msedge')
    _WD_CapabilitiesAdd('excludeSwitches', 'enable-automation')
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupEdge

Func SetupGecko($bHeadless)
    _WD_Option('Driver', 'geckodriver.exe')
    _WD_Option('DriverParams', '--log trace')
    _WD_Option('Port', 4444)
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'firefox')
    _WD_CapabilitiesAdd('browserName', 'firefox')
    _WD_CapabilitiesAdd('acceptInsecureCerts', True)
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupGecko

Func SetupOpera($bHeadless)
    _WD_Option('Driver', 'operadriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\opera.log"')
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'opera')
    _WD_CapabilitiesAdd('w3c', True)
    _WD_CapabilitiesAdd('excludeSwitches', 'enable-automation')
    _WD_CapabilitiesAdd('binary', _WD_GetBrowserPath("opera"))
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupOpera

Func _FullscreenScreenshot($sSession, $sFile)
    _WD_Window($sSession, 'rect', '{"height":1, "width":1, "x":0, "y":0}') ;This may need to be tweaked
    Local $iHeight = _WD_ExecuteScript($sSession, "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight)", Default, Default, $_WD_JSON_Value)
    Local $iWidth = _WD_ExecuteScript($sSession, "return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.body.clientWidth, document.documentElement.clientWidth)", Default, Default, $_WD_JSON_Value)
    _WD_Window($sSession, 'rect', '{"height":' & $iHeight & ', "width":' & $iWidth & ', "x":0, "y":0}')
    Local $sBodyElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByTagName, 'body')
    Local $dResponse = _WD_Screenshot($sSession, $sBodyElement, 2)
    Local $hFileOpen = FileOpen($sFile, $FO_BINARY + $FO_OVERWRITE)
    FileWrite($hFileOpen, $dResponse)
    FileClose($hFileOpen)
EndFunc  ;==>_FullscreenScreenshot

The _WD_Window command may need to be tweaked, or you can see how the screenshot looks when that command is commented out.

Edited by GMK
Clarification, Optimization
Link to post
Share on other sites

In non-headless mode, it performs the screenshot, but not the full page.  I have not tried _WD_Screenshot or _WD_PrintToPDF for this purpose, but I'll play around with it.  Thanks!

Link to post
Share on other sites

After trying _WD_Screenshot, I see that I can just combine the element action and the Base 64 decode into one command.  With _WD_PrintToPDF, I do not need to mess with resizing the window to the document size before printing to PDF.  Unfortunately, I'm not aware of a way to get _WD_PrintToPDF to output to anything other than a PDF format.

Link to post
Share on other sites

I've been playing around with this in non-headless mode (on multiple browsers) and I'm finding that it just works better in headless mode.  The resizing of the window to fit the document isn't working the same in non-headless mode as in headless mode.

Link to post
Share on other sites

did you test in both modes what values are for:
 

window.innerWidth;
window.innerHeight;

?
 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2022-03-07

Link to post
Share on other sites

Do you set your own print options or you use Default ?
 

_WD_PrintToPdf($sSession, $sOptions)

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2022-03-07

Link to post
Share on other sites

I just used default options for _WD_PrintToPDF.  I haven't taken the time to see how to format additional options (probably JSON, I'm guessing).  This is mostly because I'm not looking for a PDF solution here.

I figured the innerWidth and innerHeight had something to do with it, but I find that I don't need to be as concerned about it in headless mode. *shrug*

(Side note: I've also found that taking a full page screenshot is much more complicated when frames are involved.)

Link to post
Share on other sites
Posted (edited)

OK, I've had time to play a little more and came up with the following, which works best in headless mode for all browsers:

#include "wd_core.au3"
#include "wd_helper.au3"
#include "wd_capabilities.au3"

Global $bHeadless = True
Global $sCapabilities = SetupChrome($bHeadless)
_WD_Startup()

Global $sSession = _WD_CreateSession($sCapabilities)
If @error = $_WD_ERROR_Success Then
    Global $sURL = 'https://autoitscript.com/forum'
    _WD_Navigate($sSession, $sURL)
    _WD_LoadWait($sSession)
    Global $sFile = 'screenshot.png'
    _FullscreenScreenshot($sSession, $sFile)
    ShellExecuteWait($sFile)
EndIf
_WD_DeleteSession($sSession)
_WD_Shutdown()

Func SetupChrome($bHeadless)
    _WD_Option('Driver', 'chromedriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\chrome.log"')
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'chrome')
    _WD_CapabilitiesAdd('w3c', True)
    _WD_CapabilitiesAdd('excludeSwitches', 'enable-automation')
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupChrome

Func SetupEdge($bHeadless)
    _WD_Option('Driver', 'msedgedriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\msedge.log"')
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'msedge')
    _WD_CapabilitiesAdd('excludeSwitches', 'enable-automation')
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupEdge

Func SetupGecko($bHeadless)
    _WD_Option('Driver', 'geckodriver.exe')
    _WD_Option('DriverParams', '--log trace')
    _WD_Option('Port', 4444)
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'firefox')
    _WD_CapabilitiesAdd('browserName', 'firefox')
    _WD_CapabilitiesAdd('acceptInsecureCerts', True)
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupGecko

Func SetupOpera($bHeadless)
    _WD_Option('Driver', 'operadriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\opera.log"')
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'opera')
    _WD_CapabilitiesAdd('w3c', True)
    _WD_CapabilitiesAdd('excludeSwitches', 'enable-automation')
    _WD_CapabilitiesAdd('binary', _WD_GetBrowserPath("opera"))
    If $bHeadless Then _WD_CapabilitiesAdd('args', '--headless')
    Local $sCapabilities = _WD_CapabilitiesGet()
    Return $sCapabilities
EndFunc   ;==>SetupOpera

Func _FullscreenScreenshot($sSession, $sFile)
    _WD_Window($sSession, 'rect', '{"height":1080, "width":1920, "x":0, "y":0}')
    Local $asElements = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//div[contains(@class, 'container') or contains(@id, 'container') or contains(@name, 'container')]", Default, True)
    Local $iDIVWidth = 0, $oRect
    For $iElement = 0 To UBound($asElements) - 1
        $oRect = _WD_ElementAction($sSession, $asElements[$iElement], 'rect')
        If $oRect.Item('width') > $iDIVWidth Then $iDIVWidth = $oRect.Item('width')
    Next
    _WD_Window($sSession, 'rect', '{"height":1080, "width":' & $iDIVWidth & ', "x":0, "y":0}')
    Local $iHeight = _WD_ExecuteScript($sSession, "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight)", Default, Default, $_WD_JSON_Value)
    If Not $bHeadless Then $iHeight += 88
    Local $iWidth = _WD_ExecuteScript($sSession, "return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.body.clientWidth, document.documentElement.clientWidth)", Default, Default, $_WD_JSON_Value)
    If $iDIVWidth > $iWidth Then $iWidth = $iDIVWidth
    If Not $bHeadless Then $iWidth += 16
    Local $sBodyElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByTagName, 'body')
    $oRect = _WD_ElementAction($sSession, $sBodyElement, 'rect')
    Local $iExpand = $iWidth - $oRect.Item('width')
    _WD_Window($sSession, 'rect', '{"height":' & $iHeight & ', "width":' & $iWidth + $iExpand & ', "x":0, "y":0}')
    Local $dResponse = _WD_Screenshot($sSession, $sBodyElement, 2)
    Local $hFileOpen = FileOpen($sFile, $FO_BINARY + $FO_OVERWRITE)
    FileWrite($hFileOpen, $dResponse)
    FileClose($hFileOpen)
EndFunc  ;==>_FullscreenScreenshot

 

Edited by GMK
Removed unnecessary lines
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...