Jump to content

WebDriver example scripts collection


Recommended Posts

  • 2 months later...

Finally I was able to attach to runing Chrome instances.

Here is example script:

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

# HOW TO TEST:
; At first run choose [Yes] to create new session Chrome running instance
; At second run choose [No] to attach to active Chrome running instance

Global $_MY__WD_SESSION
Global $__g_sDownloadDir = ""

_Test()

Exit

Func _Test()
    Local $iAnswer = MsgBox($MB_YESNO + $MB_TOPMOST + $MB_ICONQUESTION + $MB_DEFBUTTON2, "Question", _
            "Open new sesion ?" & @CRLF & "[ NO ] = Try attach to active Chrome instance")
    If $iAnswer = $IDYES Then
        _Testing_CreateSession()
        Return     ; do not process next functions
    Else
        _Testing_AttachSession()
        _WD_Navigate($_MY__WD_SESSION, 'https://www.google.com/')
    EndIf

    $iAnswer = MsgBox($MB_YESNO + $MB_TOPMOST + $MB_ICONQUESTION + $MB_DEFBUTTON2, "Question", _
            "Do you want to test ?" & @CRLF & "[ NO ] = Refresh - prevent expiration")
    If $iAnswer = $IDYES Then
        _Testing_WD_Navigate()
    Else
        _Testing_Refreshing()
    EndIf

    ; CleanUp
    _WD_DeleteSession($_MY__WD_SESSION)
    _WD_Shutdown()
EndFunc   ;==>_Test

Func _Testing_CreateSession()
    $_MY__WD_SESSION = _MY__WD_SetupChrome(False, $__g_sDownloadDir, False)
EndFunc   ;==>_Testing_CreateSession

Func _Testing_AttachSession()
    $_MY__WD_SESSION = _MY__WD_SetupChrome(False, $__g_sDownloadDir, True)
EndFunc   ;==>_Testing_AttachSession

Func _Testing_Refreshing()
    While 1
;~      _WD_Navigate($_MY__WD_SESSION, '')
        _WD_Action($_MY__WD_SESSION, 'REFRESH')
        Local $iAnswer = MsgBox($MB_YESNO + $MB_TOPMOST + $MB_ICONQUESTION + $MB_DEFBUTTON2, "Question", "Finish refreshing?" & @CRLF & "[No] = Refresh - prevent expiration", 60)
        If $iAnswer = $IDYES Then Return
    WEnd
EndFunc   ;==>_Testing_Refreshing

Func _Testing_WD_Navigate()
    _WD_Navigate($_MY__WD_SESSION, 'https://www.autoitscript.com/forum')
EndFunc   ;==>_Testing_WD_Navigate

Func _MY__WD_SetupChrome($b_Headless, $s_Download_dir = Default, $bTryAttach = False)
    If $s_Download_dir = Default Then
        $s_Download_dir = ''
    ElseIf $s_Download_dir Then
        If FileExists($s_Download_dir) = 0 Then $s_Download_dir = ''
    EndIf

    _WD_UpdateDriver('chrome')
    If @error Then Return SetError(@error, @extended, '')

    _WD_Option('Driver', 'chromedriver.exe')
    _WD_Option('Port', 9515)
    _WD_CapabilitiesStartup()
;~  Local $s_AttachOption = (($bTryAttach) ? ("") : (" --remote-debugging-port=9222"))
;~  _WD_Option('DriverParams', '--log trace' & $s_AttachOption)
    _WD_CapabilitiesAdd('firstMatch', 'chrome')
    _WD_CapabilitiesAdd('w3c', True)
    _WD_CapabilitiesAdd('detach', False)
    _WD_CapabilitiesAdd('binary', "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")

    If $bTryAttach Then
            _WD_CapabilitiesAdd('debuggerAddress', '127.0.0.1:9222')
    Else
            _WD_CapabilitiesAdd('args', '--remote-debugging-port=9222')
    EndIf
    If $b_Headless Then _
            _WD_CapabilitiesAdd('args', '--headless')
    If $s_Download_dir Then _
            _WD_CapabilitiesAdd('prefs', 'download.default_directory', $s_Download_dir)

    _WD_CapabilitiesDump(@ScriptLineNumber & ' :WebDriver:Capabilities:')

    Local $iWebDriverPID = _WD_Startup()
    If @error Then Return SetError(@error, @extended, '')



    Local $s_Capabilities = _WD_CapabilitiesGet()
    Local $WD_SESSION = _WD_CreateSession($s_Capabilities)
    If @error Then Return SetError(@error, @extended, $WD_SESSION)

    Local $iBrowserPID = _WD_GetBrowserPID($iWebDriverPID, 'chrome')
    ConsoleWrite("! $iBrowserPID=" & $iBrowserPID & @CRLF)

    Return SetError(@error, @extended, $WD_SESSION)
EndFunc   ;==>_MY__WD_SetupChrome


; #FUNCTION# ====================================================================================================================
; Name ..........: _WD_GetBrowserPID
; Description ...: Get the PID of the browser that was launched by WebDriver
; Syntax ........: _WD_GetBrowserPID($iWebDriverPID, $sBrowserName)
; Parameters ....: $iWebDriverPID       - WebDriver PID returned by _WD_Startup()
;                  $sBrowserName        - [optional] Browser name from the list of supported browsers ($_WD_SupportedBrowsers)
; Return values .: Success - Browser PID
;                  Failure - 0 and sets @error to one of the following values:
;                  - $_WD_ERROR_GeneralError
;                  - $_WD_ERROR_NotSupported
;                  - $_WD_ERROR_NoMatch
; Author ........: mLipok
; Modified ......: Danp2
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _WD_GetBrowserPID($iWebDriverPID, $sBrowserName = '')
    Local Const $sFuncName = "_WD_GetBrowserPID"
    Local $iErr = $_WD_ERROR_Success, $iExt = 0, $iIndex = 0, $sBrowserExe = '', $aProcessList, $iBrowserPID = 0, $sMessage = ''
    Local $sDriverProcessName = _WinAPI_GetProcessName($iWebDriverPID)

    If @error Or Not ProcessExists($iWebDriverPID) Then
        #REMARK ProcessExists($iWebDriverPID) is required because of ; https://www.autoitscript.com/trac/autoit/ticket/3894
        $sDriverProcessName = ''
        $iErr = $_WD_ERROR_GeneralError
        $iExt = 1
        $sMessage = 'Unable to retrieve WebDriver process name for given PID'
    ElseIf _ArraySearch($_WD_SupportedBrowsers, $sDriverProcessName, Default, Default, Default, Default, Default, $_WD_BROWSER_DriverName) = -1 Then
        $iErr = $_WD_ERROR_NotSupported
        $sMessage = 'WebDriverPID is related to not supported WebDriver exe name'
    Else
        If $sBrowserName Then
            $iIndex = _ArraySearch($_WD_SupportedBrowsers, $sBrowserName, Default, Default, Default, Default, Default, $_WD_BROWSER_Name)
        EndIf
        If @error Then
            $iErr = $_WD_ERROR_GeneralError
            $iExt = 2
            $sMessage = 'BrowserName can not be found on supported browsers names list'
        Else
            $aProcessList = _WinAPI_EnumChildProcess($iWebDriverPID)
            If @error Then
                $iErr = $_WD_ERROR_GeneralError
                $iExt = 3
                $sMessage = 'Session was not created properly'
            Else
                _ArrayDisplay($aProcessList, '$aProcessList')
                ; all not supported EXE file names should be removed from $aProcessList, for example "conhost.exe" can be used by WebDriver exe file
                For $iCheck = $aProcessList[0][0] To 1 Step -1
                    _ArraySearch($_WD_SupportedBrowsers, $aProcessList[$iCheck][1], Default, Default, Default, Default, Default, $_WD_BROWSER_ExeName)
                    If @error Then
                        _ArrayDelete($aProcessList, $iCheck)
                        $aProcessList[0][0] -= 1
                    EndIf
                Next
                If $aProcessList[0][0] = 0 Then
                    $iErr = $_WD_ERROR_GeneralError
                    $iExt = 4
                    $sMessage = 'All child process (file names) are not listed on supported browsers exe'
                EndIf
            EndIf
        EndIf
    EndIf

    If $iErr = $_WD_ERROR_Success Then
        If $sBrowserName = '' Then
            $iBrowserPID = $aProcessList[1][0]
        Else
            $sBrowserExe = $_WD_SupportedBrowsers[$iIndex][$_WD_BROWSER_ExeName]
            For $i = 1 To $aProcessList[0][0]
                If $aProcessList[$i][1] = $sBrowserExe Then
                    $iBrowserPID = $aProcessList[$i][0]
                    $sMessage = "Browser - " & $aProcessList[$i][1] & " - PID = " & $iBrowserPID
                    ExitLoop
                EndIf
            Next
            If Not $iBrowserPID Then
                $iErr = $_WD_ERROR_NoMatch
                $sMessage = 'BrowserExe related to requested BrowserName was not matched in the webdriver child process list'
            EndIf
        EndIf
    EndIf
    Return SetError(__WD_Error($sFuncName, $iErr, $sMessage, $iExt), $iExt, $iBrowserPID)
EndFunc   ;==>_WD_GetBrowserPID

 

As so far the main issue was that we was trying to use:

_WD_Option('DriverParams', '--log trace  --remote-debugging-port=9222')

but it should be :

_WD_CapabilitiesAdd('args', '--remote-debugging-port=9222')

 

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

@SkysLastChance is it works for you ?

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
  • 1 month later...

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.

  • Similar Content

    • By ThomasBennett
      Good morning, everyone, 
      I am using WebDriver with ChromeDriver version 105.0.5195.52
      I have the script almost completed; this is going to be used as a wait / pause until the file has completed uploading. I was able to find where the value: "C:\\fakepath\\Vladimir Harkonnen.jpg" is stored. I am trying to figure out how to read this value. This is part of an <input type="file"> element. Reading / finding the value would be the trigger to allow the script to continue. I don't know very much but I feel like I am either not using WebDriver correctly or possibly it won't be able to help me with what I am trying to do.
      Please see the attached screenshot. 
      Thank you for your time, experience, and patience with me,




      Thomas Bennett
       

    • By TTE26
      For the past two days I've been reading all Wiki pages, installed all the demos etc. but I am still unable to do this simple workflow
      1. I want to use WebDriver UDF to open Chrome (Set chrome option arguments - Window Size, Pixel ratio, device type and platform name, user-agent.)
      2. On new Tab I want to read the tab Title and save it into a TXT file.
      3. I need to save the Session ID with my previosly set Capabilities into a file.
      4. I want to close the chrome window.
      Then
      5. I want to open Chrome again, but with my previosly saved Session ID and Capabilities list from the file.
      6. And minimaze the window state.
      7. After 30 seconds, close the chrome.
      I would really appreciate for the WebDriver UDF Helper file, to have also basic code examples, for non coders. For example how to open a windwow etc., save sessions, etc.
      Anyway, if someone could help me get started and help me with this workflow, that would be much appreaciated. 😔
    • By lapoelkan12
      hi i try to use webdriver  i download it and  download json and  winhttp i try to run it  but  return error
       error: __WinHttpVer(): undefined function.
              Local $sWinHttpVer = __WinHttpVer()
              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
       
       

    • By levila
      Hi Guys, i just do some codding to automate login to some of the web.
      I manage to do the script but somehow after script done, some weird box popup. and keep looping until i close the main chrome.exe

      here is my code. kinldy pls assist, im very new to webdriver udf.
      #NoTrayIcon #include "wd_core.au3" #include "wd_helper.au3" $_WD_DEBUG = $_WD_DEBUG_None ; You could also use $_WD_DEBUG_Error Local $sDesiredCapabilities, $sSession SetupChrome() _WD_Startup() $sSession = _WD_CreateSession($sDesiredCapabilities) _WD_Navigate($sSession, "https://someoftheweb.com") _ChromeSetInputValueByName($sSession, "inputName", "Username") _ChromeSetInputValueById($sSession, "inputPassword", "Password") _ChromeSetMouseClick($sSession, "submit", "click") _WD_Shutdown() Func SetupChrome() _WD_Option('Driver', 'chromedriver.exe') _WD_Option('Port', 9515) _WD_Option('DriverParams', '--log-path="' & @ScriptDir & '\chrome.log"') $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true, "args":["--no-sandbox"]}}}}' EndFunc Func _ChromeSetInputValueByName($sSession,$name,$Value) $sButton = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='"&$name&"']") _WD_ElementAction($sSession,$sButton,'value', $Value) EndFunc Func _ChromeSetInputValueById($sSession,$Id,$Value) $sButton = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='"&$Id&"']") _WD_ElementAction($sSession,$sButton,'value', $Value) EndFunc Func _ChromeSetMouseClick($sSession,$Id,$Value) $sButton = _WD_FindElement($sSession,$_WD_LOCATOR_ByXPath,"//button[@type='"&$Id&"']") _WD_ElementAction($sSession, $sButton, 'click', $Value) EndFunc  
    • By RohanM
      Hi Team,
      is there is a way to embed the webpage in auto it GUI using webdriver? what I want to do is that, I want to open edge browser inside the AutoIT GUI, in IE we have _IECreateEmbedded function but for the webdriver I am not able to find a function, please help  
      Rohan M
×
×
  • Create New...