Jump to content
Sign in to follow this  
Danp2

WebDriver UDF - Help & Support

Recommended Posts

23 hours ago, Danp2 said:

@nguyenthaiytcc This isn't something that I've needed to do previously, but I believe this would be the basic syntax --

$sAction = '{"actions":[{"type": "key", "id": "keyboard_1", "actions": [{"type": "keyDown", "value": "\uE00F"}, {"type": "keyUp", "value": "\uE00F"}]}]}'
_WD_Action($sSession, "actions", $sAction)

Please give it a try and report back with your results.

Like the example in Demo,

$sAction = '{"actions":[{"id":"default mouse","type":"pointer","parameters":{"pointerType":"mouse"},"actions":[{"duration":100,"x":0,"y":0,"type":"pointerMove","origin":{"ELEMENT":"'

$sAction &= $sElement & '","' & $_WD_ELEMENT_ID & '":"' & $sElement & '"}},{"button":2,"type":"pointerDown"},{"button":2,"type":"pointerUp"}]}]}'

ConsoleWrite("$sAction = " & $sAction & @CRLF)

_WD_Action($sSession, "actions", $sAction)

the sentence is long and a little incomprehensible. Can explain what kind of continuous action this paragraph represents?

Share this post


Link to post
Share on other sites
Func _WD_jQuerify($sSession)
Local $jQueryLoader = _
"(function(jqueryUrl, callback) {" & _
"    if (typeof jqueryUrl != 'string') {" & _
"        jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';" & _
"    }" & _
"    if (typeof jQuery == 'undefined') {" & _
"        var script = document.createElement('script');" & _
"        var head = document.getElementsByTagName('head')[0];" & _
"        var done = false;" & _
"        script.onload = script.onreadystatechange = (function() {" & _
"            if (!done && (!this.readyState || this.readyState == 'loaded' " & _
"                    || this.readyState == 'complete')) {" & _
"                done = true;" & _
"                script.onload = script.onreadystatechange = null;" & _
"                head.removeChild(script);" & _
"                callback();" & _
"            }" & _
"        });" & _
"        script.src = jqueryUrl;" & _
"        head.appendChild(script);" & _
"    }" & _
"    else {" & _
"        jQuery.noConflict();" & _
"        callback();" & _
"    }" & _
"})(arguments[0], arguments[arguments.length - 1]);"

_WD_ExecuteScript($sSession, $jQueryLoader, "[]", True)

Do
    Sleep(250)
    _WD_ExecuteScript($sSession, "jQuery")
Until @error = $_Cst_ERROR_Success

EndFunc
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script>
function myFunction(){
    document.getElementById("demo").innerHTML="Hello World";
}
</script>
</head>
<body>

<p>Click Trigger Function</p>
<button onclick="myFunction()" id="testclick">Click Me</button>
<p id="demo"></p>

</body>
</html>

Two problems were found in the use of this function:

1,  it had been in the loading process

     until it was discovered that the file was downloaded from the Internet.

     how to load a local file and not download it from the network?

     I rewrite it in the following form, but  sometimes I find it is not working.

2  function does not return a value.

     How do I determine if the load is successful?

If $jqFilePath <> "" Then $jqFilePath = @ScriptDir & "\jquery.min.js"
    Local $jQueryLoader = _
            "(function(jqueryUrl, callback) {" & _
            "    if (typeof jqueryUrl != 'string') {" & _
            "        jqueryUrl = '" & $jqFilePath & "';" & _
            "    }" & _

 

Share this post


Link to post
Share on other sites
31 minutes ago, Letraindusoir said:

how to load a local file and not download it from the network?

Haven't tested this, but it looks like you could pass a parameter in the first _WD_ExecuteScript line representing the alternative file that you want to load.

35 minutes ago, Letraindusoir said:

function does not return a value.   How do I determine if the load is successful?

Sorry, but don't have time to debug your code for you.

Share this post


Link to post
Share on other sites
16 minutes ago, Danp2 said:

Haven't tested this, but it looks like you could pass a parameter in the first _WD_ExecuteScript line representing the alternative file that you want to load.

Sorry, but don't have time to debug your code for you.

I think you misunderstood, not let you debug my code.

Share this post


Link to post
Share on other sites

@Letraindusoir Here's a revised version of _WD_jQuerify that you are welcome to try --

; #FUNCTION# ====================================================================================================================
; Name ..........: _WD_jQuerify
; Description ...: Inject jQuery library into current session
; Syntax ........: _WD_jQuerify($sSession[, $sjQueryFile = Default[, $iTimeout = Default]])
; Parameters ....: $sSession            - Session ID from _WDCreateSession
;                : $sjQueryFile         - [optional] Path or URL to jQuery source file
;                  $iTimeout            - [optional] Period of time to wait before exiting function
; Return values .: None
;                  @ERROR       - $_WD_ERROR_Success
;                               - $_WD_ERROR_Timeout
; Author ........: Dan Pollak
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........: https://sqa.stackexchange.com/questions/2921/webdriver-can-i-inject-a-jquery-script-for-a-page-that-isnt-using-jquery
; Example .......: No
; ===============================================================================================================================
Func _WD_jQuerify($sSession, $sjQueryFile = Default, $iTimeout = Default)
    Local Const $sFuncName = "_WD_jQuerify"

    If $sjQueryFile = Default Then
        $sjQueryFile = ""
    Else
        $sjQueryFile = '"' & StringReplace($sjQueryFile, "\", "/") & '"' ; wrap in double quotes and replace backslashes
    EndIf

    If $iTimeout = Default Then $iTimeout = $_WD_DefaultTimeout

    Local $jQueryLoader = _
    "(function(jqueryUrl, callback) {" & _
    "    if (typeof jqueryUrl != 'string') {" & _
    "        jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js';" & _
    "    }" & _
    "    if (typeof jQuery == 'undefined') {" & _
    "        var script = document.createElement('script');" & _
    "        var head = document.getElementsByTagName('head')[0];" & _
    "        var done = false;" & _
    "        script.onload = script.onreadystatechange = (function() {" & _
    "            if (!done && (!this.readyState || this.readyState == 'loaded' " & _
    "                    || this.readyState == 'complete')) {" & _
    "                done = true;" & _
    "                script.onload = script.onreadystatechange = null;" & _
    "                head.removeChild(script);" & _
    "                callback();" & _
    "            }" & _
    "        });" & _
    "        script.src = jqueryUrl;" & _
    "        head.appendChild(script);" & _
    "    }" & _
    "    else {" & _
    "        jQuery.noConflict();" & _
    "        callback();" & _
    "    }" & _
    "})(arguments[0], arguments[arguments.length - 1]);"

    _WD_ExecuteScript($sSession, $jQueryLoader, $sjQueryFile, True)

    If @error = $_WD_ERROR_Success Then
        Local $hWaitTimer = TimerInit()

        Do
            If TimerDiff($hWaitTimer) > $iTimeout Then
                SetError($_WD_ERROR_Timeout)
                ExitLoop
            EndIf

            Sleep(250)
            _WD_ExecuteScript($sSession, "jQuery")
        Until @error = $_WD_ERROR_Success
    EndIf

    Local $iErr = @error

    If $_WD_DEBUG = $_WD_DEBUG_Info Then
        ConsoleWrite($sFuncName & ': ' & $iErr & @CRLF)
    EndIf

    Return SetError(__WD_Error($sFuncName, $iErr))

EndFunc

 

The primary changes are as follows --

  • Optional parameter for alternate jQuery file to load
  • Optional parameter to adjust new timeout feature
  • Sets @error on exit

In my testing, I was able to load an alternate version of jQuery using a URL. However, passing in a local filename (even using the prefix "File:///") didn't work for me.

Share this post


Link to post
Share on other sites

Hi Damp2,

You can't help me solving my security problem (seeing my post earlier) ? Perhaps it's impossible to make something ?

THanks in advance 

Share this post


Link to post
Share on other sites

Hi @loulou2522,

Why don't we start with what you have tried thus far to solve your problem? 😏

Also, you've only given us a screenshot thus far. If you really want the community's help in solving this issue, then it would be best to post a short reproducer script that we can run to observe the issue ourselves.

Dan

Share this post


Link to post
Share on other sites

Hi @Danp2, I need your help again 😁
I need to catch an element (its css will change, d = 'XXX'). I think I should search for that element with xpath and can I somehow display the value XXX?

Edited by nguyenthaiytcc

Share this post


Link to post
Share on other sites

Hi Damp2,

Thanks for your precious help.  

Sorry because  i don't speak english very well and what i want to say is Can you help me and not you can't help  

After research , I found the way to avoid this message  by modifying chrome config  

Here is the solution :

================================
To deactivate this  file message in chrome "This type of file can damage your computer" for xml files, for other type of file this is the same thing to do 
go to 😄\Users\%Username\%localappData\Local\Google\Chrome\User Data\FileTypePolicies\40 open the file download_file_types.pb
and delete the xml extension
;===================================

 

Edited by loulou2522

Share this post


Link to post
Share on other sites
2 hours ago, Danp2 said:

Hi @loulou2522 ,

I understood the question, but wanted you to do the research instead of depending on someone else to do it. 🙂

Glad you found a solution. I assume you tried it and it worked.

Regards,

Dan

 

Yes but i have a problem. When i launch manually  chrome that's works perfectly but when i launc it with chrome driver the message reappears

It seem that the profile loaded is not the same because manually send and automatic execution 

I launch with 

Func SetupChrome()
    _WD_Option('Driver', 'chromedriver.exe')
    _WD_Option('Port', 9515)
   _WD_Option('DriverParams', '--log-path="' & @ScriptDir & '\chrome.log"')
      _WD_Option('DriverParams','--user-data-dir="C:\Users\xxx\AppData\Local\Google\Chrome\User Data\Default"')
    $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"unhandledPromptBehavior": "ignore", ' & _
    '"goog:chromeOptions": {"w3c": true, "excludeSwitches": ["enable-automation"], "useAutomationExtension": false, ' & _
    '"prefs": {"credentials_enable_service": false}, "args": ["start-maximized"] }}}}'


EndFunc   ;==>SetupChrome

 

Share this post


Link to post
Share on other sites
28 minutes ago, loulou2522 said:

Yes but i have a problem. When i launch manually  chrome that's works perfectly but when i launc it with chrome driver the message reappears

Right... you'll need to figure out how to use the correct profile in Chrome. This has been discussed multiple times on the forum, so I believe your answer can already be found in this thread.

Share this post


Link to post
Share on other sites

I think I have detected a problem in the chrome driver. Indeed in the case of use of a specific profile during the normal shutdown of the program and that I send the following commands;

WD_DeleteSession ($ sSession)
and_WD_Shutdown ()

Chrome closes normally but when reopened I get the following message "Restore pages? Chrome did not shut down properly" <RESTORE>
If I close the program the following way

If ProcessExists ("chrome.exe") Then
$ aList = WinList ()
For $ i = 1 To $ aList [0] [0]
If StringInStr ($ aList [$ i] [0], "Google Chrome")> 0 And BitAND (WinGetState ($ aList [$ i] [1]), 2) Then
Sleep (200)

WinClose ($ aList [$ i] [1])
EndIf
Next
EndIf

If ProcessExists ("chromedriver.exe") Then
Local $ hWnd = WinWait ("[REGEXPTITLE: (chromedriver.exe)]", "", 1)
WinClose ($ hWnd)
EndIf


then the programm restarts without error message

 

Here is the code which allow to test this problem 

 

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Outfile_x64=toto.exe
#AutoIt3Wrapper_UseUpx=y
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Res_Language=1036
#AutoIt3Wrapper_Res_requestedExecutionLevel=requireAdministrator
#Au3Stripper_Parameters=/sf /sv
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

Opt("MustDeclareVars", 0)
Opt("MouseCoordMode", 1)
Opt("WinTitleMatchMode", 4)
Opt("SendKeyDelay", 100)
Opt("SendKeyDownDelay", 5)
Opt("CaretCoordMode", 0)
Opt("WinWaitDelay", 550)
Opt("MouseClickDelay", 20)
Opt("TrayIconDebug", 1)
Opt("PixelCoordMode", 0)

 Global  $echrome = True
 Global  $Ssession,$sDesiredCapabilities

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


;================================================
;Recherche d la langue du systéme d'exploitation
;=============================================


    SetupChrome()

_WD_Startup()
Sleep(1000)


$sSession = _WD_CreateSession($sDesiredCapabilities)
;_WD_Window($sSession, 'Maximize')


    _WD_Navigate($sSession, "http://www.google.com")
    _WD_LoadWait($sSession,  500, -1)
    _WD_DeleteSession($sSession)
    _WD_Shutdown()

Func SetupChrome()
    ;======================================

    _WD_Option('Driver', 'chromedriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--log-path="' & @ScriptDir & '\chrome.log"')
    $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": { "acceptInsecureCerts":true, "unhandledPromptBehavior": "ignore","goog:chromeOptions": {"w3c": true, "excludeSwitches": ["enable-automation"], "useAutomationExtension": false,"prefs": {"credentials_enable_service": false}, "args":["start-minimized","--user-data-dir=C:\\Users\\' & @UserName & '\\AppData\\Local\\Google\\Chrome\\User Data\\",  "disable-infobars"]}}}}'
EndFunc   ;==>SetupChrome

After you have to relaunch the programm and you get this message :

image.thumb.png.362600116f92c32e69bddfd019c95a14.png

Edited by loulou2522

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By goku200
      I'm having some issues with writing to column C when an element is found. It works on C2 but it does not continue to C3, C4, C5, etc..... I'm wanting to write "test" if the element //input[@id='username'] is found  $someUser = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='username']"). I have attached my HTML and Excel file along with my AutoIt code below:
      #Include "wd_core.au3" #Include "wd_helper.au3" #Include "wd_core.au3" #Include "File.au3" #Include "Array.au3" #Include "Excel.au3" Local $sDesiredCapabilities, $sSession _WD_Startup() $Ssession = _WD_CreateSession($sDesiredCapabilities) _WD_Navigate($sSession, "https://127.0.0.1/test.html") _WD_LoadWait($sSession) Local $oExcel = _Excel_Open() Local $oWorkbook = _Excel_BookOpen($oExcel, "C:\Users\<Username>\Downloads\test.xlsx") Local $aArrayTest1 = _Excel_RangeRead($oWorkbook, 1, $oWorkbook.ActiveSheet.Usedrange.Columns("A:A")) Local $aArrayTest2 = _Excel_RangeRead($oWorkbook, 1, $oWorkbook.ActiveSheet.Usedrange.Columns("B:B")) For $i = 0 To UBound($aArrayTest1) - 1 _WD_Navigate($Ssession, $aArrayTest1[$i]) _WD_LoadWait($sSession) $someUser = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='username']") _WD_SetElementValue($sSession, $someUser, $aArrayTest2[$i]) Local $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@type='submit'][@value='Submit']") _WD_ElementAction($sSession, $sElement, 'click') _WD_LoadWait($sSession) Sleep(5000) If $someUser Then Local $aArray2D[2] = ["test"] _Excel_RangeWrite($oWorkbook, $oWorkbook.ActiveSheet, $aArray2D, "C2") EndIf Next 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":["start-maximized","disable-infobars"]}}}}' EndFunc ;==>SetupChrome  
      test.html test.xlsx
    • By goku200
      I'm having some issues with my script that's not grabbing the id from the cell and appending it to the url test that I have in my script.
      Here is my script:
      #Include "wd_core.au3" #Include "wd_helper.au3" #Include "wd_core.au3" #Include "File.au3" #Include "Array.au3" #Include "Excel.au3" #Include "INet.au3" Local $sDesiredCapabilities, $sSession _WD_Startup() $Ssession = _WD_CreateSession($sDesiredCapabilities) _WD_Navigate($sSession, "https://127.0.0.1/test.html?id=1");session is created. When tabed on browser it will populate url _WD_LoadWait($sSession) $someUser = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@name='username']") _WD_SetElementValue($sSession, $someUser, "test") $somePassword = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@name='password']") _WD_SetElementValue($sSession, $somePassword, "test") Local $aVar[1] _ArrayAdd ($aVar,_WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@type='submit'][@value='Sign in']")) _WD_ElementAction($sSession, $aVar[1], 'click') _WD_LoadWait($sSession) Local $oExcel = _Excel_Open() Local $oWorkbook = _Excel_BookOpen($oExcel, "C:\Users\<Username>\Downloads\test.xlsx") Local $aArray1 = _Excel_RangeRead($oExcel, 1) _ArrayDisplay($aArray1, "Vertical") For $i = 0 To UBound($aArray) - 1 WinActivate("[Class:Chrome]") $testLink = "https://127.0.0.1/test.html?id=" _WD_Navigate($sSession, $testLink) $aArray1 = ClipGet() _WD_NewTab($Ssession, clipPut($testLink), True) Send("{ENTER}") Local $test = InetGet($testLink + $aArray1, "C:\Users\<username>\Downloads\Test" & ".html") Send ("!s");save webpage as html Next 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":["start-maximized","disable-infobars"]}}}}' EndFunc ;==>SetupChrome What I'm having issues is looping through the id column in the excel spreadsheet and adding 1 to the url address when its tabbed by using _WD_NewTab. When it goes to the browser I'm wanting it to display: https://127.0.0.1/test.html?id=1 press Enter and save the file as 1.html and so forth for the others. Not sure what I'm doing wrong here. 
      test.xlsx
    • By Danp2
      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 few configuration settings.
      Requirements
      JSON UDF https://www.autoitscript.com/forum/topic/148114-a-non-strict-json-udf-jsmn
      WinHTTP UDF https://www.autoitscript.com/forum/topic/84133-winhttp-functions/
      HtmlTable2Array UDF (optional) https://www.autoitscript.com/forum/topic/167679-read-data-from-html-tables-from-raw-html-source/
      WebDriver for desired browser
      Chrome WebDriver https://sites.google.com/a/chromium.org/chromedriver/downloads FireFox WebDriver https://github.com/mozilla/geckodriver/releases Edge WebDriver https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ Source Code
      You will always be able to find the latest version in the GitHub Repo 
      Help / Support
      See the wiki for details on the UDF --
      https://www.autoitscript.com/wiki/WebDriver
      Please post any questions, suggestions or errors in the GH&S thread.
      https://www.autoitscript.com/forum/topic/201106-webdriver-udf-help-support-ii/
    • By Jgladden
      Dan - thanks for all that you do - this stuff is great. 
      Hoping you can assist with an issue we are having now that we have moved to Windows 10/Server 2016. The Chrome interactions were working flawlessly until moving over. Now my code fails when attempting to create the session. As you can see, our Chrome install is not in a standard location but I have validated the path to the binary. I have attached some detail below including system info, console output and the chrome log detail. I have tried several recommendations that have seen in various forums but none have made a difference
      Any assistance you can give would be greatly appreciated. 
      Thanks in advance, 
      chrome_Details.txt
    • By Langmeister
      I am once again asking for your experienced assistance. If I open a website that uses notifications I am asked to allow or block them for that website after a few seconds. This notification pops up every time the page gets navigated to, even tho you have clicked on allow for several times. I am explicitly not searching for smth to get rid of "Chrome is being controlled by automated test sw". Instead I am searching for a line of script to disable all notifications by default: like here chrome://settings/content/notifications. 
      This is code should give you an example of what notifications I am talking about:
      #include "wd_core.au3" #include "wd_helper.au3" Local $sDesiredCapabilities, $sSession, $sID _WD_Option("Driver", "C:\Program Files (x86)\AutoIt3\chromedriver.exe") _WD_Option('Port', 9515) _WD_Option('DriverParams', '--log-path="' & @ScriptDir & '\chrome.log"') $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true }}}}' _WD_Startup() $sSession = _WD_CreateSession($sDesiredCapabilities) _WD_Navigate($sSession, "https://webradio.planetradio.de/") _WD_LoadWait($sSession)  
×
×
  • Create New...