Jump to content

WebDriver UDF (W3C compliant version) - 2023/02/15


Recommended Posts

  • Replies 1k
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Popular Posts

Latest update just released. See below for change log.  

Latest update just released. See below for change log.  

Introduction This UDF will allow you to interact with any browser that supports the W3C WebDriver specifications. Supporting multiple browsers via the same code base is now possible with just a f

Posted Images

Yeah, i'm using $_WD_LOCATOR_ByID and $_WD_LOCATOR_ByClassName in a few places in the older part of my script as I hadn't learned xpath yet.

I suppose it wouldn't be to hard to update those to XPath.

 

edit, the $_WD_LOCATOR_ByID="id" which is used in 2 functions.  Is the "id" ok to use in _WD_FrameEnter(), _WD_ElementAction()?

Edited by BigDaddyO
Link to post
Share on other sites

Please show me some working examples where it you were using $_WD_LOCATOR_ByID and $_WD_LOCATOR_ByClassName.

2 hours ago, BigDaddyO said:

Is the "id" ok to use in _WD_FrameEnter(), _WD_ElementAction()?

Don't confuse a locator type with a parameter being passed to the webdriver. The Switch to Frame specs call for a json key named "id", where the associated value is either null, an integer index, or a web element. I'm sure the specs are similar for interacting with elements.

 

Link to post
Share on other sites

I've already finished converting those over to xpath as it was very simple.  I'm testing a softphone and there are a few elements that have nothing but an id or class and they are unique so they used to work fine but the conversion to xpath was super simple.  I had never used xpath before using your UDF's.  Perhaps some xpath help links could be added to the first post as it seems to be VERY important to be able to really use this properly.

For me, I got a lot of help from these 3 site.  Also, it took a while to realize that xpath is case sensitive

https://www.guru99.com/xpath-selenium.html

https://www.guru99.com/using-contains-sbiling-ancestor-to-find-element-in-selenium.html

https://gist.github.com/LeCoupa/8c305ec8c713aad07b14

 

 

As for some examples of what I was using vs how I converted over to xpath

ByClassName:  if _WD_WaitElement($sSession, $_WD_LOCATOR_ByClassName, "ctiSoftphone", 2000, 120000) = 0 Then

Switched to:  if _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//div[@class='ctiSoftphone']", 2000, 120000) = 0 Then

 

ByID:  $oExtension = _WD_FindElement($sSession, $_WD_LOCATOR_ByID, "ab120f6a04114d5bab4cfc96abc75da1_PRIMARY_LINE_NUMBER")

Switched to:  $oExtension = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[contains(@id, 'PRIMARY_LINE_NUMBER')]")

 

Link to post
Share on other sites
15 minutes ago, BigDaddyO said:

ByID:  $oExtension = _WD_FindElement($sSession, $_WD_LOCATOR_ByID, "ab120f6a04114d5bab4cfc96abc75da1_PRIMARY_LINE_NUMBER")

Switched to:  $oExtension = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[contains(@id, 'PRIMARY_LINE_NUMBER')]")

I know you are using Chrome, which isn't completely up to snuff with the W3C specs at this time. Did you try this with a different browser? I suspect that it won't work, but would need to test to be sure.

Link to post
Share on other sites

@Danp2 Same as BigDaddyO, I didn't know anything about xpath until recently when I had to change my codes. I changed all my ByID strategies to ByXPath and they all work fine in my chromedriver. I always appreciate your efforts to make the webdriver easier to use.

By the way, I find that the $sSelector part of the _WD_FindElement function must be enclosed in double quotes: "//input[@id='login-id']" works, but '//input[@id="login-id"]' doesn't. Is this by design?

Edited by CYCho
Link to post
Share on other sites
2 hours ago, CYCho said:

By the way, I find that the $sSelector part of the _WD_FindElement function must be enclosed in double quotes: "//input[@id='login-id']" works, but '//input[@id="login-id"]' doesn't. Is this by design?

Thanks for pointing that out. I take a look to see if there's an easy fix.

Link to post
Share on other sites

<a href="javascript:MemberCheck('2');">Search</a>

<a href="javascript:MemberCheck('3');">Search</a>

These are the links I want to click using chromedriver.

Since the text is same for both links, I tried _WD_LinkClickByText($sSession, "javascript:MemberCheck('2');"), which failed.

Maybe I should try _WD_FindElement, but I don't know how to handle 3 sets of quotation marks in $sSelector. HTML character codes do not seem to work here.

Please give me a hint to solve this problem. 

Link to post
Share on other sites
On 8/9/2018 at 3:26 AM, CYCho said:

By the way, I find that the $sSelector part of the _WD_FindElement function must be enclosed in double quotes: "//input[@id='login-id']" works, but '//input[@id="login-id"]' doesn't. Is this by design?

This appears to be a JSON limitation. You can make it work by escaping the double quotes, like this --

$sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, '//input[@id=\"lst-ib\"]')

 

Link to post
Share on other sites
  • 2 weeks later...

hi 

I used _WD_Window($sSession, 'frame', '{"id":1}') to solve my problem. Now I need to enable flash support. What do I need to do in _WD_Option()?

Following code :

"profile.default_content_setting_values.plugins": 1,
"profile.content_settings.plugin_whitelist.adobe-flash-player": 1,
"profile.content_settings.exceptions.plugins.*,*.per_resource.adobe-flash-player": 1,
"PluginsAllowedForUrls": "http://www.xxx.cc"

my code:

$EnableFlash = '{"prefs":{"profile":{"default_content_setting_values":{"plugins": 1}},{"content_settings":{"plugin_whitelist":{"adobe-flash-player":1},{"exceptions":{"plugins":{"*":{"*":{"per_resource":{"adobe-flash-player":1}}}}}}}}},{"PluginsAllowedForUrls": "http://www.xxx.cc"}}'

$sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"chromeOptions": {"w3c": true},'&$EnableFlash&'}}}'

error:

__WD_Post: URL=HTTP://127.0.0.1:9515/session; $sData={"capabilities": {"alwaysMatch": {"chromeOptions": {"w3c": true},{"prefs":{"profile":{"default_content_setting_values":{"plugins": 1}},{"content_settings":{"plugin_whitelist":{"adobe-flash-player":1},{"exceptions":{"plugins":{"*":{"*":{"per_resource":{"adobe-flash-player":1}}}}}}}}},{"PluginsAllowedForUrls": "http://www.xxx.cc"}}}}}
__WD_Post: StatusCode=400; ResponseText=missing command parameters
_WD_CreateSession: missing command parameters
_WD_CreateSession ==> Webdriver Exception

 

flash.png

Edited by nulee
Link to post
Share on other sites
  • 3 weeks later...

Hey all. Not sure I should post this there, but since ages when automatizing tests with AutoIt I ran into the simple issue that I always lack the possibility to retrieve the HTTP code returned by the request in my navigator. When you do heavy automations, it's painfull to need to retrive from JS (or other ways) an URI and then do another HTTP request manually in your script to check the HTTP statuscode. (Making another request, and possibly not the same answer than what you had in your navigator).

Looking into this library instead of the old deprecated FF.au3 (with Mozrepl), I saw sadly it's still true and WebDriver specification dosn't allow us to retrieve this HTTP statuscode.

However I was able this time to find another way to retrieve it, by parsing FF logs, so I share it if someone else need that. This works with FF only, but there is a way to do the same thing with Chrome if needed ( All you need to do is tell chrome driver to do "Network.enable". This can be done by enabling Performance logging).

 

I modified a little bit _WD_Option (see attached) to allow set another option :

_WD_Option('FFLogFile', _TempFile(@ScriptDir&"\fflogs\"))

If this value is set, I simply set two environment variables before the start of Firefox, thus I'm able to read FF logs, parse them and retrieve from them my HTTP Statuscode.

 

Func _WD_GetHTTPStatusCode_FFOnly($URI)
    Local Const $sFuncName = "_WD_GetLastHTTPStatusCode"
    Local $uriID = ""

    $sFilePath = $_WD_Firefox_LogFile
    If $sFilePath = "" Then Return SetError(__WD_Error($sFuncName, $_WD_ERROR_InvalidValue, "You need to set option of LogFile in order to be able to retrieve HTTP statuscode"))
    Local $hFileOpen = FileOpen($sFilePath, 0)
    If $hFileOpen = -1 Then
        Return SetError(__WD_Error($sFuncName, $_WD_ERROR_InvalidValue, "Unable to open FF log file"))
    EndIf
    Local $sFileRead = FileRead($hFileOpen)

    ; this is how the log looks like when the request starts
    ; I have to get the id of the request using a regular expression
    ; and use that id later to get the response
    ;
    ;    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::BeginConnect [this=000000BFF27A5000]
    ;    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp host=api.ipify.org port=-1
    ;    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp uri=https://api.ipify.org/?format=text

    Local $pattern = "(?is)BeginConnect \[this=(.*?)\](?:.*?)uri=([^\]]+?)\R"
    $aRet = StringRegExp($sFileRead,$pattern,3)
    For $i = 1 To UBound($aRet) - 1 Step 2
        If $aRet[$i] = $URI Then
            $uriID = $aRet[$i-1]
            ContinueLoop
        EndIf
    Next

    If $uriID = "" THen Return SetError(__WD_Error($sFuncName, $_WD_ERROR_InvalidValue, "Unable to find related URI in FF logs to retrieve HTTP statuscode"))


    ; this is how the response looks like in the log file
    ; ProcessResponse [this=000000CED8094000 httpStatus=200]
    ; I will use another regular espression to get the httpStatus
    ;
    ;    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=000000CED8094000 request=000000CED8014BB0 status=0]
    ;    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]

    Local $pattern = "(?is)ProcessResponse \[this="&$uriID&" httpStatus=(.*?)\]";
    $aRet = StringRegExp($sFileRead,$pattern,1)
    FileClose($hFileOpen)
    Return $aRet[0]
EndFunc

 

And simple example :

$URI = "http://www.autoitscript.com/404/"
_WD_Navigate($sSession, $URI)
MsgBox(0,"",_WD_GetHTTPStatusCode_FFOnly($URI))

$URI = "https://www.autoitscript.com/forum/topic/191990-webdriver-udf-w3c-compliant-version-08042018/"
_WD_Navigate($sSession, $URI)
MsgBox(0,"",_WD_GetHTTPStatusCode_FFOnly($URI))

 

wd_core.au3

Link to post
Share on other sites

This Function helped me alot so i decided to share it with u ;)

;Add this to wd-core.au3
#Region Global Variables
Global $_WD_ResolveTimeout = Default, _
       $_WD_ConnectTimeout = Default, _
       $_WD_SendTimeout = Default, _
       $_WD_ReceiveTimeout = Default, _
#EndRegion Global Variables

;Add this ligne to wd-core.au3 under "_WinHttpOpen()" in (__WD_Get/__WD_Post/__WD_Delete) Functions
_WinHttpSetTimeouts($hOpen, $_WD_ResolveTimeout, $_WD_ConnectTimeout, $_WD_SendTimeout, $_WD_ReceiveTimeout)

;Add this function to wd-core.au3 or wd-helper.au3 or in ur own script
; #FUNCTION# ;===============================================================================
; Name...........: _WD_WinHttpTimeouts
; Description ...:
; Syntax.........: _WD_WinHttpTimeouts([, $sResolveTimeout = '' [, $sConnectTimeout = '' [, $iSendTimeout = '' [, $iReceiveTimeout = '' ]]]])
; Parameters ....: $sResolveTimeout - [optional] Time-out value, in milliseconds, to use for name resolution.
;                  $sConnectTimeout - [optional] Time-out value, in milliseconds, to use for server connection requests.
;                  $sSendTimeout - [optional] Time-out value, in milliseconds, to use for sending requests.
;                  $sReceiveTimeout - [optional] Time-out value, in milliseconds, to receive a response to a request.
; Return values .: Success      - Timeouts
; Author ........: OmarJr16
; Modified ......:
; Remarks .......: Initial values are:
;                  |- $sResolveTimeout = 0
;                  |- $sConnectTimeout = 60000
;                  |- $sSendTimeout = 30000
;                  |- $sReceiveTimeout = 30000
; Related .......:
; Link ..........: http://msdn.microsoft.com/en-us/library/aa384116.aspx
; Example .......: No
;============================================================================================
Func _WD_WinHttpTimeouts($sResolveTimeout = '', $sConnectTimeout = '', $sSendTimeout = '', $sReceiveTimeout = '')
    If $sResolveTimeout <> '' Then _
        $_WD_ResolveTimeout = $sResolveTimeout
    If $sConnectTimeout <> '' Then _
        $_WD_ConnectTimeout = $sConnectTimeout
    If $sSendTimeout <> '' Then _
        $_WD_SendTimeout = $sSendTimeout
    If $sReceiveTimeout <> '' Then _
        $_WD_ReceiveTimeout = $sReceiveTimeout
    $Timeouts =('{"timeout":{"resolve":' & $_WD_ResolveTimeout & ',"connect":' & $_WD_ConnectTimeout & ',"send":' & $_WD_SendTimeout & ',"receive":' & $_WD_ReceiveTimeout)
    If $_WD_DEBUG = $_WD_DEBUG_Info Then _
        ConsoleWrite($Timeouts)
    Return $Timeouts
EndFunc
Edited by omarjr16
Link to post
Share on other sites

Please edit your example as follow:

//Add this ligne to wd-core.au3 under "_WinHttpOpen()" in (__WD_Get/__WD_Post/__WD_Delete) Functions

should be:

; Add this ligne to wd-core.au3 under "_WinHttpOpen()" in (__WD_Get/__WD_Post/__WD_Delete) Functions

as this 

//

is not a comment sign/character in AutoIt

 

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) * Show_Macro_Values.au3 *

 

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: 2023-03-02

Link to post
Share on other sites

I use an old function from SmOke_N to close chrome since chromedriver.exe spawns child processes that were not closing with the normal _WD_Shutdown()

 

;Testing Chrome browser as Headless to run on a server after disconnecting from RDP
#AutoIt3Wrapper_UseX64=n
#include "wd_core.au3"
#include "wd_helper.au3"

$_WD_DEBUG = $_WD_DEBUG_None        ;set to $_WD_DEBUG_None before compiling.

    $sWebSite = "https://www.autoitscript.com/site/autoit/downloads/"
;~  $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"chromeOptions": {"w3c": true, "useAutomationExtension": false, "args":["start-maximized", "disable-infobars"] }}}}' ;This will display Chrome Full screen and inteact with it
    $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"chromeOptions": {"w3c": true, "useAutomationExtension": false, "args":["headless", "disable-gpu", "disable-infobars"] }}}}' ;This will launch Chrome in a Headless mode, Use _WD_Startup(True) to completely hide

MsgBox(0, "Wait for close", "This script will now wait 30 seconds before automatically continuing" & @CRLF & @CRLF & "Please disconnect from RDP to test without an Active Desktop", 30)


    _SetupChrome()

    $iPID = _WD_Startup()                                                               ;Return the PID of the ChromeDriver.exe as we will need it to close when done

    $sSession = _WD_CreateSession($sDesiredCapabilities)
    _WD_Timeouts($sSession, '{"type":"page load","ms":120000}')     ;Increase the default timeout.

    _WD_Navigate($sSession, $sWebSite)

    If _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//div/table[1]/tbody/tr/td[2]", 1000, 20000, True) <> 1 Then
        ConsoleWrite("Error, Item not found" & @CRLF)
        Exit
    EndIf

    $eVer = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//div/table[1]/tbody/tr/td[1]")
    $sVer = _WD_ElementAction($sSession, $eVer, "text")

    $eDate = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//div/table[1]/tbody/tr/td[2]")
    $sDate = _WD_ElementAction($sSession, $eDate, "text")

ConsoleWrite(@CRLF & "*** Latest AutoIT version = ( " & $sVer & " )" & @CRLF & "*** Release Date = ( " & $sDate & " )" & @CRLF & @CRLF)


;New section since Chromedriver and chrome windows werent closing
$aSpawnedChildren = _ProcessGetChildren($iPID)          ;Get all processes spawned directly from the Chromedriver.exe
ProcessClose($iPID)                                                         ;Close the Chromedriver.exe
For $x = 0 to UBound($aSpawnedChildren) - 1                 ;Move through every child process
    ProcessClose($aSpawnedChildren[$x][0])                      ;Close the child process
Next


;From SmOke_N
;https://www.autoitscript.com/forum/topic/78445-solved-parent-process-child-process/
Func _ProcessGetChildren($i_pid) ; First level children processes only
    Local Const $TH32CS_SNAPPROCESS = 0x00000002

    Local $a_tool_help = DllCall("Kernel32.dll", "long", "CreateToolhelp32Snapshot", "int", $TH32CS_SNAPPROCESS, "int", 0)
    If IsArray($a_tool_help) = 0 Or $a_tool_help[0] = -1 Then Return SetError(1, 0, $i_pid)

    Local $tagPROCESSENTRY32 = _
    DllStructCreate _
    ( _
    "dword dwsize;" & _
    "dword cntUsage;" & _
    "dword th32ProcessID;" & _
    "uint th32DefaultHeapID;" & _
    "dword th32ModuleID;" & _
    "dword cntThreads;" & _
    "dword th32ParentProcessID;" & _
    "long pcPriClassBase;" & _
    "dword dwFlags;" & _
    "char szExeFile[260]" _
    )
    DllStructSetData($tagPROCESSENTRY32, 1, DllStructGetSize($tagPROCESSENTRY32))

    Local $p_PROCESSENTRY32 = DllStructGetPtr($tagPROCESSENTRY32)

    Local $a_pfirst = DllCall("Kernel32.dll", "int", "Process32First", "long", $a_tool_help[0], "ptr", $p_PROCESSENTRY32)
    If IsArray($a_pfirst) = 0 Then Return SetError(2, 0, $i_pid)

    Local $a_pnext, $a_children[11][2] = [[10]], $i_child_pid, $i_parent_pid, $i_add = 0
    $i_child_pid = DllStructGetData($tagPROCESSENTRY32, "th32ProcessID")
    If $i_child_pid <> $i_pid Then
    $i_parent_pid = DllStructGetData($tagPROCESSENTRY32, "th32ParentProcessID")
    If $i_parent_pid = $i_pid Then
    $i_add += 1
    $a_children[$i_add][0] = $i_child_pid
    $a_children[$i_add][1] = DllStructGetData($tagPROCESSENTRY32, "szExeFile")
    EndIf
    EndIf

    While 1
    $a_pnext = DLLCall("Kernel32.dll", "int", "Process32Next", "long", $a_tool_help[0], "ptr", $p_PROCESSENTRY32)
    If IsArray($a_pnext) And $a_pnext[0] = 0 Then ExitLoop
    $i_child_pid = DllStructGetData($tagPROCESSENTRY32, "th32ProcessID")
    If $i_child_pid <> $i_pid Then
    $i_parent_pid = DllStructGetData($tagPROCESSENTRY32, "th32ParentProcessID")
    If $i_parent_pid = $i_pid Then
    If $i_add = $a_children[0][0] Then
    ReDim $a_children[$a_children[0][0] + 11][2]
    $a_children[0][0] = $a_children[0][0] + 10
    EndIf
    $i_add += 1
    $a_children[$i_add][0] = $i_child_pid
    $a_children[$i_add][1] = DllStructGetData($tagPROCESSENTRY32, "szExeFile")
    EndIf
    EndIf
    WEnd

    If $i_add <> 0 Then
    ReDim $a_children[$i_add + 1][2]
    $a_children[0][0] = $i_add
    EndIf

    DllCall("Kernel32.dll", "int", "CloseHandle", "long", $a_tool_help[0])
    If $i_add Then Return $a_children
    Return SetError(3, 0, 0)
EndFunc



Func _SetupChrome()

    If _WD_Option('Driver', 'chromedriver.exe') = 0 Then Return SetError(1)

    If _WD_Option('Port', 9515) = 0 Then Return SetError(1)

    If _WD_Option('DriverParams', '--log-path="' & @ScriptDir & '\chrome.log"') = 0 Then Return SetError(1)

EndFunc   ;==>_SetupChrome

 

edit:  updated for the current version of the UDF, this just ensures all spawned chrome windows are closed.

 

Edited by BigDaddyO
Link to post
Share on other sites
  • Danp2 changed the title to WebDriver UDF (W3C compliant version) - 2023/02/15
  • Melba23 pinned this topic

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 Blaxxun
      Hello,
      I open a new thread here since i dont want to hijack the thread of @water  called "I'm creating a WebDriver tutorial".
      As recommended i started to take a deeper look into the "GDPR fines.au3" example.
      I also fount that "au3WebDriver-0.11.0" comes with a nice Help file "Webdriver.chm"
      When running GDPR fines.au3 i noticed that it uses a function called:
      _WD_GetTable($sSession, $sBaseElement, $iPage)
      It has 3 function parameters and is IN the "GDPR fines.au3"

      So i got an error: wrong number of args.
      Further investigation showed me that this function is already defined in the "wd_helper.au3" which is loaded at the beginnings #include but has only 2 parameters.
      So i commented out the function in the "wd_helper.au3"

      The _WD_GetTable function ran error free now but the next stop was:
      _WD_ElementOptionSelect($sSession, $_WD_LOCATOR_ByXPath, "//select[@name='penalties_length']//option[contains(text(),'" & $aOptions[UBound($aOptions, 1) - 2] & "')]")
      Variable subscript badly formatted (Error at -> UBound)
       
      I'm not really sure why this happens because i dont really know how to traverse a website yet.
      Have to dig deeper and read into it more.
    • By corvo
      Hello!

      I've been trying to launch chrome through WD,  but for some reason, the user profile is not working, it just opens up the chrome window with the "temp" user. I've also made sure that the user profile path is correct by using "chrome://version". 
      Here is what I've got so far:
      #include "wd_helper.au3" #include "wd_capabilities.au3" #include "wd_core.au3" SetupChrome() _WD_CapabilitiesStartup() Local $sCapabilities = _WD_CapabilitiesGet() $sSession = _WD_CreateSession($sCapabilities) _WD_Navigate($sSession, "https://www.google.com") Func SetupChrome() _WD_Option('Driver', 'chromedriver.exe') _WD_Option('Port', 9515) _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\chrome.log"') _WD_Option('DriverParams', '--marionette-port 2828') $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true, "args":["--user-data-dir=C:\\Users\\' & @UserName & '\\AppData\\Local\\Google\\Chrome\\User Data\\", "--profile-directory=Profile 2"]}}}}' $_WD_DEBUG = $_WD_DEBUG_None ; You could also use $_WD_DEBUG_Error EndFunc  
      Thanks in advance!
       
    • By ThomasBennett
      Good morning, everyone, 
      I have had very good luck with using _WD_ElementActionEx 'CLICKANDHOLD'. What would be the best practice with dragging and dropping web elements? I would prefer to not to have to use any dragging and dropping but I haven't figured out a way to change the order the elements are displayed programmatically. 
      I have a list of elements that are drag and drop. These elements in code are using <UL></UL> for the entire list and the actual web elements that are being manipulated are in <LI></LI> tags. These do not look like a bulleted list but that is the code that is being used. I've spoken with the web developer and there isn't any hot keys or keyboard commands that can be used to move these elements.
      I know where the new and original web element appears and can select them using the _WD_WaitElement and _WD_FindElement combo. I can find the number of items in the list by looking at the code; I haven't started pulling the values out just yet. I am trying to figure out if there is a place to change the listed order.
      Using the 'CLICKANDHOLD' feature as part of _WD_ElementActionEx does work and I know more or less where I need to drop it the new web element; the problem I am having is scrolling exactly to where I need the new web element dropped. It should be dropped beneath the original web element. 
      What's the best method to output the number of children associated with the <UL></UL>? I am guessing that _WD_ElementActionEx 'CHILDCOUNT' would be it; but I haven't figured out how to get the call to output in a msgbox or in the console. 
      #cs ---------------------------------------------------------------- Name ..........: Please Note!.au3 Description ...: To be used to add new lessons to existing playlists and to update the pre-existing lesson with the Please Note! PowerPoint SciTE 32-bit ..: Version 4.4.6 Author(s) .....: Thomas E. Bennett Date ..........: 20220929 Recommended Reading / Requirements https://www.autoitscript.com/forum/topic/191990-webdriver-udf-w3c-compliant-version-01162021/#comments https://www.autoitscript.com/wiki/WebDriver https://www.autoitscript.com/wiki/WebDriver#Installation https://www.autoitscript.com/wiki/Adding_UDFs_to_AutoIt_and_SciTE https://www.autoitscript.com/autoit3/docs/intro/running.htm#CommandLine wd_core.au3 wd_helper.au3 From wd_core.au3 Global Const $_WD_LOCATOR_ByCSSSelector = "css selector" Global Const $_WD_LOCATOR_ByXPath = "xpath" Global Const $_WD_LOCATOR_ByLinkText = "link text" Global Const $_WD_LOCATOR_ByPartialLinkText = "partial link text" Global Const $_WD_LOCATOR_ByTagName = "tag name" #ce ---------------------------------------------------------------- #include "wd_core.au3" #include "wd_helper.au3" #include <MsgBoxConstants.au3> #include <Excel.au3> #include <AutoItConstants.au3> Local $sDesiredCapabilities, $sSession, $sElement ; Create application object and open an example workbook Local $oExcel = _Excel_Open() If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example", "Error creating the Excel application object." & @CRLF & "@error = " & @error & ", @extended = " & @extended) Local $oWorkbook = _Excel_BookOpen($oExcel, @ScriptDir & "\{PRIVACY}.xlsx") If @error Then MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example", "Error opening workbook '" & @ScriptDir & "\{PRIVACY}.xlsx'." & @CRLF & "@error = " & @error & ", @extended = " & @extended) _Excel_Close($oExcel) Exit EndIf ; Read data from a single cell on the active sheet of the specified workbook ;Local $sResult = _Excel_RangeRead($oWorkbook, Default, "A1") ;If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example 1", "Error reading from workbook." & @CRLF & "@error = " & @error & ", @extended = " & @extended) ;MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example 1", "Data successfully read." & @CRLF & "Value of cell A1: " & $sResult) SetupChrome() _WD_Startup() $sSession = _WD_CreateSession($sDesiredCapabilities) Sleep (15000) Local $aResult = _Excel_RangeRead($oWorkbook, Default, "A16:E16") For $i = 0 To UBound($aResult, 1) - 1 ;ConsoleWrite("========= Start Row =========" & @CRLF) ;ConsoleWrite($aResult[$i][0] & @CRLF) ; Column A -- Course Playlist Number ;ConsoleWrite($aResult[$i][1] & @CRLF) ; Column B -- Course Playlist Title ;ConsoleWrite($aResult[$i][2] & @CRLF) ; Column C -- Original Lesson Title ;ConsoleWrite($aResult[$i][3] & @CRLF) ; Column D -- Updated Lesson Number ;ConsoleWrite($aResult[$i][4] & @CRLF) ; Column E -- Updated Lesson Title ;ConsoleWrite("========= End Row =========" & @CRLF & @CRLF) _WD_Navigate($sSession, "{PRIVACY}" & $aResult[$i][0]) _WD_LoadWait($sSession, 2000) ; Find the Available Lessons search box and enter the appropriate value _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='titleSearch']") $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='titleSearch']") ; Click the Sign in button _WD_ElementAction($sSession, $sElement, 'value', $aResult[$i][3]) Send("{Enter}") ; Find the correct "Add" hyperlink _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//span[text()='" & $aResult[$i][4] & "']/following-sibling::div") $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//span[text()='" & $aResult[$i][4] & "']/following-sibling::div") ; Click the "Add" hyperlink _WD_ElementAction($sSession, $sElement, 'click') ; Number of Child Elements _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//ul[@id='selected-items']") $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//ul[@id='selected-items']") _WD_ElementActionEx($sSession, $sElement, 'CHILDCOUNT') Exit ; Click and Hold the appropriate element _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//ul[@id='selected-items']//span[@class='item-description' and text()='" & $aResult[$i][4] & "']/parent::li") $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//ul[@id='selected-items']//span[@class='item-description' and text()='" & $aResult[$i][4] & "']/parent::li") _WD_ElementActionEx($sSession, $sElement, 'clickandhold', 0, 0, 0, 10000) ; Hover the appropriate element _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//ul[@id='selected-items']//span[@class='item-description' and text()='" & $aResult[$i][4] & "']/following-sibling::a") $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//ul[@id='selected-items']//span[@class='item-description' and text()='" & $aResult[$i][4] & "']/following-sibling::a") _WD_ElementActionEx($sSession, $sElement, 'HOVER') Exit Next Exit _WD_DeleteSession($sSession) _WD_Shutdown() Exit Func SetupChrome() ; Google Chrome _WD_Option('Driver', "C:\Users\thomas.bennett\Desktop\AutoIt\include\chromedriver.exe") _WD_Option('Port', 9515) ;_WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\chrome.log"') $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"unhandledPromptBehavior": "ignore", ' & _ '"goog:chromeOptions": {"w3c": true, "excludeSwitches": ["enable-automation"], "useAutomationExtension": false, ' & _ '"prefs": {"credentials_enable_service": false},' & _ '"args": ["start-maximized"] }}}}' EndFunc Console Output
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\Users\thomas.bennett\Desktop\AutoIt\Please Note!\Please Note!.au3" /UserParams +>09:22:40 Starting AutoIt3Wrapper (21.316.1639.1) from:SciTE.exe (4.4.6.0) Keyboard:00000409 OS:WIN_10/2009 CPU:X64 OS:X64 Environment(Language:0409) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\thomas.bennett\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\thomas.bennett\AppData\Local\AutoIt v3\SciTE >Running AU3Check (3.3.14.5) from:C:\Program Files (x86)\AutoIt3 input:C:\Users\thomas.bennett\Desktop\AutoIt\Please Note!\Please Note!.au3 +>09:22:40 AU3Check ended.rc:0 >Running:(3.3.14.5):C:\Program Files (x86)\AutoIt3\autoit3.exe "C:\Users\thomas.bennett\Desktop\AutoIt\Please Note!\Please Note!.au3" +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. _WD_Option ==> Success [0] : Parameters: Option=Driver Value=C:\Users\thomas.bennett\Desktop\AutoIt\include\chromedriver.exe _WD_Option ==> Success [0] : Parameters: Option=Port Value=9515 _WD_IsLatestRelease ==> Success [0] : True _WD_Startup: OS: WIN_10 WIN32_NT 22000 _WD_Startup: AutoIt: 3.3.14.5 _WD_Startup: Webdriver UDF: 0.10.1 (Up to date) _WD_Startup: WinHTTP: 1.6.4.2 _WD_Startup: Driver: C:\Users\thomas.bennett\Desktop\AutoIt\include\chromedriver.exe (32 Bit) _WD_Startup: Params: _WD_Startup: Port: 9515 _WD_Startup: Command: "C:\Users\thomas.bennett\Desktop\AutoIt\include\chromedriver.exe" _WD_Startup ==> Success [0] __WD_Post ==> Success [0] : HTTP status = 200 _WD_CreateSession ==> Success [0] : 2542b35e47b8f9b2558cd92ad1418811 __WD_Post ==> Success [0] : HTTP status = 200 _WD_Navigate ==> Success [0] : Parameters: URL={PRIVACY} _WD_LoadWait ==> Success [0] : Parameters: Delay=2000 Timeout=Default Element=Default _WD_WaitElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@id='Username'] Delay=Default Timeout=Default Options=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_FindElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@id='Username'] StartNodeID=Default Multiple=Default ShadowRoot=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_ElementAction ==> Success [0] : Parameters: Command=value Option=<masked> _WD_WaitElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@id='Password'] Delay=Default Timeout=Default Options=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_FindElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@id='Password'] StartNodeID=Default Multiple=Default ShadowRoot=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_ElementAction ==> Success [0] : Parameters: Command=value Option=<masked> _WD_WaitElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@value='Sign In'] Delay=Default Timeout=Default Options=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_FindElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@value='Sign In'] StartNodeID=Default Multiple=Default ShadowRoot=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_ElementAction ==> Success [0] : Parameters: Command=click Option=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_Navigate ==> Success [0] : Parameters: URL={PRIVACY} _WD_LoadWait ==> Success [0] : Parameters: Delay=2000 Timeout=Default Element=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_Navigate ==> Success [0] : Parameters: URL={PRIVACY} _WD_LoadWait ==> Success [0] : Parameters: Delay=2000 Timeout=Default Element=Default _WD_WaitElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@id='titleSearch'] Delay=Default Timeout=Default Options=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_FindElement ==> Success [0] : Parameters: Strategy=xpath Selector=//input[@id='titleSearch'] StartNodeID=Default Multiple=Default ShadowRoot=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_ElementAction ==> Success [0] : Parameters: Command=value Option=<masked> _WD_WaitElement ==> Timeout [7] : Parameters: Strategy=xpath Selector=//span[text()='{PRIVACY}']/following-sibling::div Delay=Default Timeout=Default Options=Default __WD_Post ==> No match [8] : HTTP status = 404 _WD_FindElement ==> No match [8] : Parameters: Strategy=xpath Selector=//span[text()='{PRIVACY}']/following-sibling::div StartNodeID=Default Multiple=Default ShadowRoot=Default __WD_Post ==> No match [8] : HTTP status = 404 _WD_ElementAction ==> No match [8] : Parameters: Command=click Option=Default _WD_WaitElement ==> Success [0] : Parameters: Strategy=xpath Selector=//ul[@id='selected-items'] Delay=Default Timeout=Default Options=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_FindElement ==> Success [0] : Parameters: Strategy=xpath Selector=//ul[@id='selected-items'] StartNodeID=Default Multiple=Default ShadowRoot=Default __WD_Post ==> Success [0] : HTTP status = 200 _WD_ExecuteScript ==> Success [0] _WD_ElementActionEx ==> Success [0] : Parameters: Element=21c01052-8b86-4058-b8f6-d9dfa750f9ee Command=CHILDCOUNT XOffset=Default YOffset=Default Button=Default HoldDelay=Default Modifier=Default +>09:23:20 AutoIt3.exe ended.rc:0 +>09:23:20 AutoIt3Wrapper Finished. >Exit code: 0 Time: 40.88  

      My thought is once AutoIt knows how many child elements there are; I am hoping that there would be a way to change the sort or priority order that the <LI></LI>'s are shown in. 
      Thank you for your time and efforts on this and as I progress I'll update this topic, 




      Thomas 
    • By ThomasBennett
      #cs ---------------------------------------------------------------- Name ..........: ignore.au3 Description ...: Testing _WD_HighlightElements SciTE 32-bit ..: Version 4.4.6 Author(s) .....: Thomas E. Bennett Date ..........: 20220929 Recommended Reading / Requirements https://www.autoitscript.com/forum/topic/191990-webdriver-udf-w3c-compliant-version-01162021/#comments https://www.autoitscript.com/wiki/WebDriver https://www.autoitscript.com/wiki/WebDriver#Installation https://www.autoitscript.com/wiki/Adding_UDFs_to_AutoIt_and_SciTE https://www.autoitscript.com/autoit3/docs/intro/running.htm#CommandLine wd_core.au3 wd_helper.au3 From wd_core.au3 Global Const $_WD_LOCATOR_ByCSSSelector = "css selector" Global Const $_WD_LOCATOR_ByXPath = "xpath" Global Const $_WD_LOCATOR_ByLinkText = "link text" Global Const $_WD_LOCATOR_ByPartialLinkText = "partial link text" Global Const $_WD_LOCATOR_ByTagName = "tag name" #ce ---------------------------------------------------------------- #include "wd_core.au3" #include "wd_helper.au3" #include "wd_cdp.au3" #include "wd_capabilities.au3" #include <MsgBoxConstants.au3> Local $sDesiredCapabilities, $sElement, $sSession Func SetupChrome() ; Google Chrome _WD_Option('Driver', @ScriptDir & "\include\chromedriver.exe") _WD_Option('Port', 9515) ;_WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\chrome.log"') $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"unhandledPromptBehavior": "ignore", ' & _ '"goog:chromeOptions": {"w3c": true, "excludeSwitches": ["enable-automation"], "useAutomationExtension": false, ' & _ '"prefs": {"credentials_enable_service": false},' & _ '"args": ["start-maximized"] }}}}' EndFunc SetupChrome() _WD_Startup() $sSession = _WD_CreateSession($sDesiredCapabilities) Sleep (15000) ; DuckDuckGo _WD_Navigate($sSession, "https://duckduckgo.com/") _WD_LoadWait($sSession, 2000) ; Find the Search field _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='search_form_input_homepage']") $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='search_form_input_homepage']") ; Highlight the Search field _WD_HighlightElements($sSession, $sElement, 3) MsgBox(0,"","") Exit ;this is here on purpose _WD_DeleteSession($sSession) _WD_Shutdown() Exit Good evening, everyone, 
      I am trying to get any element to highlight using the _WD_HighlightElements function; I've tried different elements and for a time I thought maybe because I am working in Windows 11 so I switched back to Windows 10 same issue; I can't get the found element to highlight. What am I doing incorrectly?
      Console Output _WD_FindElement: {"value":{"element-6066-11e4-a52e-4f735466cecf":"0e212d4f-8437-42a0-a56a-bc8694fe6e66"}} _WD_WaitElement ==> Success __WD_Post: URL=HTTP://127.0.0.1:9515/session/0e05f8ea99dba06bb84908b0b46fe881/element; $sData={"using":"xpath","value":"//input[@id='search_form_input_homepage']"} __WD_Post: StatusCode=200; ResponseText={"value":{"element-6066-11e4-a52e-4f735466cecf":"0e212d4f-8437-42a0-a56a-bc8694fe6e66"}}... _WD_FindElement: {"value":{"element-6066-11e4-a52e-4f735466cecf":"0e212d4f-8437-42a0-a56a-bc8694fe6e66"}} Thank you for your time on this,




      Thomas E. Bennett
    • By SkysLastChance
      I am having trouble finding a good way to click these "button" below. 

      I only need to be able to click them when they have both yes/no. Otherwise I don't have to worry about them. For instance if they looked like this I would NOT have worry about clicking them and can just ignore them all togheter.(Below Picture)

      The problem is as mentioned in the title, all of the ID's  are dynamic. (Classes too)

      Here is what it looks like if yes is already selected.

      This is what I was using to select the the button. However, I need to know if the button has already been clicked/selected or not.
      _WD_LoadWait($sSession) $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//span[text() = 'Offered access to electronic health information?']") Sleep(1000) _WD_ElementAction($sSession, $sElement, 'click') Sleep(500) _WD_Action($sSession, "actions", $sActionTab) Sleep(500) _WD_Action($sSession, "actions", $sActionEnter) Is there a way I can get the count of spans in the span class-"s_636" by tabbing over to the button? I am hoping someone might have some ideas on what I can try.
      Unfortunally, The site is for work so giving the site wont do any good. 
×
×
  • Create New...