Jump to content
Danp2

WebDriver UDF - Help & Support

Recommended Posts

50 minutes ago, Letraindusoir said:

Are there any actual examples where '$sStartElement' is not empty? I don't quite understand when $sStartElement is used

It's used when you want to perform an element search starting at a particular element. For example, if you want to get all the rows from a table, first you retrieve the element ID for the table. Then you use this as the starting point for your subsequent find operation, like this --

$sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "/html/body/table")
$aRows = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//tbody/tr", $sElement, True)

 

Share this post


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

It's used when you want to perform an element search starting at a particular element. For example, if you want to get all the rows from a table, first you retrieve the element ID for the table. Then you use this as the starting point for your subsequent find operation, like this --

$sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "/html/body/table")
$aRows = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//tbody/tr", $sElement, True)

 

Thank you, Dan. I basically understand....

Share this post


Link to post
Share on other sites

To stay logged in after first time logged in I'm saving a local profile for the future reuse. My code is as follows:

$sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true, "args":["start-maximized", "disable-infobars","--user-data-dir=' & StringReplace(@ScriptDir, Chr(92), Chr(92) & Chr(92)) & '\\Profile 1"] }}}}'

So when I run script first time, I do some checks and then log in if needed (I have to do that manually first time, it's can't be automated). After that I can easily end/start my script and authentication is there ('coz of cookies). But my problem is error suggesting to restore my last session tabs.

Restore pages?
Chrome didn't shut down correctly.
[Restore]

How can I avoid this error?

I'm using this code on exit:

Func _QuitChrome()
    _WD_Window($sSession, 'Close')
    _WD_DeleteSession($sSession)
EndFunc

Func _Exit()
    _QuitChrome()
    _WD_Shutdown()
    Exit
EndFunc

UPD: I guess --disable-features=InfiniteSessionRestore should do the trick (will test it later)?..

Edited by MONaH-Rasta
Found possible sollution

Share this post


Link to post
Share on other sites

So... After some research and bunch of tests I finally have a solution to get rid of this annoying popup.

I'm using chrome version 74.0.3729.169 (current) latest stable.

Here is a code of function that will do the trick.

$sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true, "args":["start-maximized", "disable-infobars", "--user-data-dir=' & StringReplace(@ScriptDir, Chr(92), Chr(92) & Chr(92)) & '\\Profile 1"] }}}}'

    _SetPreferences()
    _WD_Startup()

Func _SetPreferences()
Local $sFileName, $sFind, $sReplace, $iRetval
    $sFileName = @ScriptDir & Chr(92) & 'Profile 1' & Chr(92) & 'Local State'
    $sFind = '"exited_cleanly":false'
    $sReplace = '"exited_cleanly":true'

    $iRetval = _ReplaceStringInFile($sFileName, $sFind, $sReplace)
    If $iRetval = -1 Then
        If TrayItemGetState($iShowNotify) = 65 Then _TrayTip('File ' & Chr(92) & 'Local State' & Chr(92) & ' was not edited! Error = ' & @error)
    EndIf

    $sFileName = @ScriptDir & Chr(92) & 'Profile 1' & Chr(92) & 'Default' & Chr(92) & 'Preferences'
    $sFind = '"exit_type":"Crashed"'
    $sReplace = '"exit_type":"None"'

    $iRetval = _ReplaceStringInFile($sFileName, $sFind, $sReplace)
    If $iRetval = -1 Then
        If TrayItemGetState($iShowNotify) = 65 Then _TrayTip('File ' & Chr(92) & 'Local State' & Chr(92) & ' was not edited! Error = ' & @error)
    EndIf
EndFunc

If you will have those 2 options set like this before start new session, chrome will start normally regardless of was he actually crashed or not. For some reason in most cases webdriver causing chrome set those 2 options to values like after "crash", and of course my solution is not "correct", but at least I have no popups now 😎

Share this post


Link to post
Share on other sites

@Letraindusoir If you look at the underlying code for _WD_Startup, you'll see the Run command that launches the console app. The setting of $_WD_DEBUG controls whether the console is launched hidden or visible. So you have two options --

  • Set the value of $_WD_DEBUG to something other than $_WD_DEBUG_Info before calling _WD_Startup
  • Use the function _WD_ConsoleVisible to change the console's visibility

Share this post


Link to post
Share on other sites

Hi @Danp2, Thank you for the UDF. It works great !! I was trying to change the default download folder of chrome. I need to map a network drive for downloads everytime session is initiated. Could you please help.

Share this post


Link to post
Share on other sites

I am running a basic script which picks up URL, Username and Password as command line parameters and initiates a web session on a RDS server as a remote application. But the session is always initiated with default Chrome settings and maps default downloads folder to the session. So I want to map the network drive as download location every time script is executed. I am really new to AutoIT so any help is much appreciated. I am really new to AutoIT so any suggestions are welcome. The code looks like:

Local $sDesiredCapabilities, $sSession

SetupChrome()

_WD_Startup()


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 }}}}'
EndFunc

If $CmdLine[0] <> 3 Then
   MsgBox($MB_OK, "Usage", "ps_palo <hostname> <username> <password>")
Else
   palo_login($CmdLine[1],$CmdLine[2],$CmdLine[3])
EndIf

Func palo_login($url,$username,$password)

   Local $string, $sButton
   $sSession = _WD_CreateSession($sDesiredCapabilities)
   $string= "https://" & $url
   _WD_Navigate($sSession,$string)

   ;Sleep(5000)
   ;_WD_LinkClickByText($sSession,"Continue to this website (not recommended).")


   _ChromeSetInputValueById($sSession,"user",$username)
   Sleep(1000)
   _ChromeSetInputValueById($sSession,"passwd",$password)
   Sleep(1000)
   $sButton = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@id='submit']")
   _WD_ElementAction($sSession, $sButton, 'click')

EndFunc ;==>PaloAlto_login()


Func _ChromeSetInputValueById($sSession,$Id,$Value)
   Local $sElement
   $sElement=_WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//input[@name='"&$Id&"']")
   _WD_ElementAction($sSession,$sElement,'value',$value)
EndFunc

;_WD_DeleteSession($sSession)
;_WD_Shutdown()

Share this post


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

@Letraindusoir If you look at the underlying code for _WD_Startup, you'll see the Run command that launches the console app. The setting of $_WD_DEBUG controls whether the console is launched hidden or visible. So you have two options --

  • Set the value of $_WD_DEBUG to something other than $_WD_DEBUG_Info before calling _WD_Startup
  • Use the function _WD_ConsoleVisible to change the console's visibility

Thank You,Dan.I See.I didn't read the UDF carefully and clearly enough.

Edited by Letraindusoir

Share this post


Link to post
Share on other sites

How do I know I got multiple results from "_WD_FindElement", does it return an array (tried)?

$sList = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//div[@class='listing-content']")
_WD_ElementAction($sSession, $sList, 'text')

In this example I know there are multiple classname "listing-content" but only see text from the first one.

Edited by Arlen

Share this post


Link to post
Share on other sites

Recently, I was thinking about a question: how can I move the mouse to the location of the element after getting an Element?

As shown like below:

$sElem = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "Xpath_sElem")
_WD_MoveMouseTo($sSession,$sElem)
or
_WD_SetFocus($sSession,$sElem)

 

Share this post


Link to post
Share on other sites
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

20180610155716143.png.8b4f1e61258abad77cb72299c62efbf5.png

As shown above, can this modal box pop-up window be controlled by a custom UDF similar to _ WD_Alert?

Edited by Letraindusoir

Share this post


Link to post
Share on other sites
1 hour ago, Danp2 said:

@Letraindusoir You can always write a custom function to serve a particular purpose. Have you tried using the standard webdriver UDF functions to interact with this dialog?

Yes, using standard functions and specific xpath,can interact with a  specific Modal_dialog_box. However, since the Modal_dialog_box is a characteristic pop-up interface, it may be more convenient and practical to encapsulate the operations For Modal_dialog_box into UDF, like _WD_Alert, can identify any Alert Pop-up.

Edited by Letraindusoir

Share this post


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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • 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/
      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/ Function List
      Core Functions
      _WD_CreateSession($sDesiredCapabilities='{}') _WD_DeleteSession($sSession) _WD_Status() _WD_Timeouts($sSession, $sTimeouts = '') _WD_Navigate($sSession, $sURL) _WD_Action($sSession, $sCommand) _WD_Window($sSession, $sCommand, $sOption = '') _WD_FindElement($sSession, $sStrategy, $sSelector, $sStartElement = "", $lMultiple = False) _WD_ElementAction($sSession, $sElement, $sCommand, $sOption='') _WD_ExecuteScript($sSession, $sScript, $sArguments="[]") _WD_Alert($sSession, $sCommand, $sOption = '') _WD_GetSource($sSession) _WD_Cookies($sSession, $sCommand, $sOption = '') _WD_Option($sOption, $vValue = "") _WD_Startup() _WD_Shutdown() Helper Functions
      _WD_NewTab($sSession, $lSwitch = True, $iTimeout = -1, $sURL = "", $sFeatures = "") _WD_Attach($sSession, $sString, $sMode = 'title') _WD_LinkClickByText($sSession, $sText, $lPartial = True) _WD_WaitElement($sSession, $sElement, $sStrategy, $sSelector[, $iDelay = 0[, $iTimeout = -1]]) _WD_GetMouseElement($sSession) _WD_GetElementFromPoint($sSession, $iX, $iY) _WD_LastHTTPResult() _WD_GetFrameCount() _WD_IsWindowTop() _WD_FrameEnter($sIndexOrID) _WD_FrameLeave() _WD_HighlightElements($sSession, $aElements[, $iMethod = 1]) _WD_jQuerify($sSession[, $sjQueryFile = Default[, $iTimeout = Default]]) _WD_ElementOptionSelect($sSession, $sStrategy, $sSelector, $sStartElement = "") _WD_ElementSelectAction($sSession, $sSelectElement, $sCommand) _WD_ConsoleVisible($lVisible = False) _WD_LoadWait($sSession[, $iDelay = 0[, $iTimeout = -1[, $sElement = '']]]) _WD_Screenshot($sSession, $sElement = '', $nOutputType = 1) _WD_SelectFiles($sSession, $sStrategy, $sSelector, $sFilename) _WD_GetShadowRoot($sSession, $sStrategy, $sSelector, $sStartElement = "") _WD_IsLatestRelease() _WD_UpdateDriver($sBrowser[, $sInstallDir = Default[, $lFlag64 = Default[, $lForce = Default]]]) _WD_DownloadFile($sURL, $sDest) Source Code
      You will always be able to find the latest version in the GitHub Repo 
      Help / Support
      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 JohnWIlling
      We are running on a VIrtual Machine via Remote Desktop.  We are having a situation where the loading of the chromedriver.exe is taking longer on the VM than on a physical machine.  It is causing the first call to  WD_Post in _WD_CreateSession to fail.
      To workaround the Issue, I used a simplified version of (_WinAPI_GetTcpTable) UDF to Loop waiting for the driver port to be in the listening state.  At that point, I know that the Post will work:
      Func _WaitForPort($ListenPort) Do Local $tMIB_TCPTABLE = DllStructCreate("dword[6]") Local $aRet = DllCall("Iphlpapi.dll", "DWORD", "GetTcpTable", "struct*", $tMIB_TCPTABLE, "DWORD*", 0, "BOOL", True) Local $dwSize = $aRet[2] $tMIB_TCPTABLE = DllStructCreate("DWORD[" & $dwSize / 4 & "]") $aRet = DllCall("Iphlpapi.dll", "DWORD", "GetTcpTable", "struct*", $tMIB_TCPTABLE, "DWORD*", $dwSize, "BOOL", True) If $aRet[0] <> 0 Then Return SetError(1) Local $iNumEntries = DllStructGetData($tMIB_TCPTABLE, 1, 1) Local $aRes[$iNumEntries][6] For $i = 0 To $iNumEntries - 1 Local $Type = DllStructGetData($tMIB_TCPTABLE, 1, 2 + $i * 5 + 0) $aRet = DllCall("ws2_32.dll", "ushort", "ntohs", "uint", DllStructGetData($tMIB_TCPTABLE, 1, 2 + $i * 5 + 2)) ; local port Local $Port = $aRet[0] ConsoleWrite("Checking Row:" & $i & " State:<" & $Type & "> Port:<" & $Port & ">" & @CRLF) ; Type 2 is LISTENING If $Type = 2 And $Port = $ListenPort Then Return 1; EndIF Next Sleep(500); Until 0; Return 0; EndFunc ;==>_WaitForPort  
    • By svenjatzu
      hey hi
      someone please can help me translate my code to be valid for udf webriver?
       
      #RequireAdmin Opt("WinTitleMatchMode",2) ;~ Sleep(10000) ShellExecute("C:\neu\1.lnk") ;~ Sleep(3000) ;~ $PID = ShellExecute("C:\freeneu\tab.exe") ;~ Sleep(30000*5) WinWait("Example Domain - Iron","") Global $sWinTitle = "Example Domain - Iron" Global $avWinList = WinList($sWinTitle) While $avWinList[0][0] < 1 Sleep(250); Wait for new process to create its GUI $avWinList = WinList($sWinTitle) WEnd For $n = 1 To $avWinList[0][0] WinActivate($avWinList[$n][1]) WinMove($avWinList[$n][1], "", 0, 0, 230, 440) Next Opt("WinTitleMatchMode",1) WinWait("Iron") Sleep(5333) WinWait("Iron") Opt("WinTitleMatchMode",2) WinWaitActive("m:") WinWait("m:") WinClose("m:") ;~ Sleep(5000) Sleep(1000) ;~ ProcessClose("tab.exe") ShellExecute(@ScriptDir & "\q2.exe")  
    • By water
      Internet Explorer is nearly dead, newer versions of Firefox can't any longer be automated using Stilgar's FF UDF.
      Hence more and more users (including me) need to look at automating Webbrowsers using WebDriver.
      That's why I have started to create a tutorial in the wiki.
      It should describe all necessary steps from intallation to usage.

      I'm still collecting ideas for the tutorial - that's where you come into play.
      What do you expect to see in such a tutorial?
      Which browsers should be covered (Firefox, Chrome and Edge are settled)? Any questions for the FAQ? Which (high level) coding examples do you expect (like "How to attach to a running browser instance") ... Like to see your comments
       
      ToDo-List:
      Add "Tools" section and add ChroPath plugin. Done. FAQ: "How to attach to a running browser instance". Done. Explain the difference between iuiautomation, iaccessible, autoit, webdriver. Done. The AutoIt FAQ 40 has been extended. Detailed description of each function. Done Example for "how to deal with downloading". Use function _WD_DownloadFile. Example for "how to deal with popups (alerts, print or save dialog). Use function_WD_AlertRespond to respond to a user prompt. Example for "how to deal with multiple tabs". Use functions _WD_NewTab (create a new tab), _WD_Window (close or switch to a tab) and _WD_Attach (attach to existing tab).
    • By water
      The WebDriver UDF provides a toolbox full of functions to facilitate automating Web browsers.
      Still scripts can become quite complex.
      In this thread users can post "real life" examples to show how specific tasks can be implemented.
      Note
      When posting an example please describe the purpose of the script and the WebDriver functionality used!
       
×
×
  • Create New...