Jump to content

WebDriver example scripts collection


water
 Share

Recommended Posts

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!
 

Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

What this script does
Extracts the list of GDPR fines from website enforcementttracker.com and returns a 2D array holding all items.

N.B. The numbers of the following list can be found in the script as comments.

WebDriver functionality used

  1. Tested with Firefox
  2. Start geckodriver to automate Firefox from a different location (needs to be modified by you in the scripts source)
  3. Maximize the browser window
  4. Retrieve all values from the "Show n entries" dropdown and select the second to last (50 entries)
  5. Sort the table by clicking on a table header
  6. Scroll to the end of the page
  7. Search and click a button

GDPR fines Version 1.au3

GDPR fines Version 2.au3

Edited by water
#4 has been enhanced: Now retrieves all values from the "Show n entries" dropdown and selects the second to last (50 entry). Was hardcoded before.

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

  • 5 weeks later...

@water In GDPR fines.au3 you are using 

_WD_ElementOptionSelect($sSession, $_WD_LOCATOR_ByXPath, "//select[@name='penalties_length']//option[contains(text(),'100')]")
    If @error Then Return SetError(@error)

Would you be so nice and explain in a new example, a way to retrieve (as an array), a list of option from this element:

<select name="penalties_length" aria-controls="penalties" class=""><option value="10">10</option><option value="25">25</option><option value="50">50</option><option value="100">100</option></select>

 

btw.
I finally start to work with WebDriver UDF, soon will post more questions, examples, functions, my proposals.

Edited by mLipok

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 * How to ask ChatGPT for AutoIt Codefor 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-04-24

Link to comment
Share on other sites

@mLipok Here's a simple way to do it --

$sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//select[@name='penalties_length']")
$sText = _WD_ElementAction($sSession, $sElement, 'property', 'innerText')
$aOptions = StringSplit ( $sText, @LF,  $STR_NOCOUNT)
_ArrayDisplay($aOptions)

If you would rather process each element individually, then this gets them into an array for further processing --

$aElements = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//select[@name='penalties_length']//option", Default, True)
_ArrayDisplay($aElements)

 

Link to comment
Share on other sites

I have modified the example above accordingly.

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

  • 3 months later...

Example script using the new _WD_ElementActionEx function --

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

Local $sDesiredCapabilities, $sSession
SetupGecko()
_WD_Startup()
$sSession = _WD_CreateSession($sDesiredCapabilities)
_WD_Navigate($sSession, "http://demo.guru99.com/test/simple_context_menu.html")
$sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//button[contains(text(),'Double-Click Me To See Alert')]")

If @error = $_WD_ERROR_Success Then
    _WD_ElementActionEx($sSession, $sElement, "doubleclick")
EndIf

Sleep(2000)
_WD_Alert($sSession, 'accept')

$sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//span[@class='context-menu-one btn btn-neutral']")

If @error = $_WD_ERROR_Success Then
    _WD_ElementActionEx($sSession, $sElement, "rightclick")
EndIf

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

Func SetupGecko()
_WD_Option('Driver', 'geckodriver.exe')
_WD_Option('DriverParams', '--log trace')
_WD_Option('Port', 4444)

$sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"browserName": "firefox", "acceptInsecureCerts":true}}}'
EndFunc

 

Link to comment
Share on other sites

  • 11 months later...
  • 7 months later...

This 2 scripts shows how to attach to a running sessions of WebDriver.

Run this following wd_demoAttachFireFox_Main.au3

#include <MsgBoxConstants.au3>
#include "wd_capabilities.au3"
#include "wd_helper.au3"

_Example()
_WD_Shutdown()

Func _Example()
    ; initialize WD
    Local $sSession = _MY__WD_SetupFireFox(False)
    If @error Then Return SetError(@error, @extended)

    ; navigate to some website
    _WD_Navigate($sSession, "http://google.com")

    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, @ScriptName, "Wait before attach")
    ; run the demo in separate thread
    Run(@AutoItExe & ' "' & @ScriptDir & '\wd_demoAttachFireFox_Secondary.au3" ', @ScriptDir)
    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, @ScriptName, "Wait before end")
EndFunc   ;==>_Example

Func _MY__WD_SetupFireFox($b_Headless)
    _WD_UpdateDriver("firefox", @ScriptDir, Default, Default)

    _WD_Option('Driver', 'geckodriver.exe')
    _WD_Option('DriverParams', '--log trace --marionette-port 2828')
    _WD_Option('Port', 4444)
    _WD_Option('DefaultTimeout', 1000)

    _WD_Startup()
    If @error Then Return SetError(@error, @extended, '')

    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch')
    _WD_CapabilitiesAdd('acceptInsecureCerts', True)
    _WD_CapabilitiesAdd('firstMatch', 'firefox')

    If $b_Headless Then _
            _WD_CapabilitiesAdd('args', '--headless')

    _WD_CapabilitiesDump(@ScriptLineNumber & ':WebDriver: Capabilities')
    Local $s_Capabilities = _WD_CapabilitiesGet()

    Local $WD_SESSION = _WD_CreateSession($s_Capabilities)
    Return SetError(@error, @extended, $WD_SESSION)
EndFunc   ;==>_MY__WD_SetupFireFox

and this following wd_demoAttachFireFox_Secondary.au3  will be run automatically

#include <MsgBoxConstants.au3>
#include "wd_helper.au3"

_Example()

Func _Example()
    _WD_Option('Driver', 'geckodriver.exe')
    _WD_Option('DriverParams', '--log trace --connect-existing  --marionette-port 2828')
    _WD_Option('Port', 4444)
    _WD_Startup()
    Local $sSession = _WD_CreateSession()

    _WD_Navigate($sSession, "https://www.autoitscript.com/forum")
    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, @ScriptName, "After attaching")
    _WD_Shutdown()
EndFunc   ;==>_Example

 

How this works?
Firstly wd_demoAttachFireFox_Main.au3 runs first WebDriver instance (will runs first instance of geckodriver.exe  to automate new instance of firefox)
After that wd_demoAttachFireFox_Main.au3 runs  wd_demoAttachFireFox_Secondary.au3 (runs second WebDriver instance, which will runs second instance of geckodriver.exe  to attach to an existing/already runing firefox instance ).

 

EDIT:

If you find this works well, I will edit AutoIt WebDriver Wiki page.

 

Edited by mLipok
script edited, script renamed

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 * How to ask ChatGPT for AutoIt Codefor 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-04-24

Link to comment
Share on other sites

On 1/28/2022 at 12:12 AM, mLipok said:

If you find this works well, I will edit AutoIt WebDriver Wiki page.

Already edited.

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 * How to ask ChatGPT for AutoIt Codefor 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-04-24

Link to comment
Share on other sites

Example using _WD_ElementSelectAction() and _WD_ElementOptionSelect() contains information how to get list of options, currently selected value, and selecting options (by Value, Text, Index)

#include <Array.au3>
#include <MsgBoxConstants.au3>
#include "wd_helper.au3"
#include "wd_capabilities.au3"

_Example()

Func _Example()

    ; If you want to download/update dirver the next line should be uncommented
;~  _WD_UpdateDriver('chrome')

    Local $WD_SESSION = SetupChrome()

    Local $sFilePath = _WriteTestHtml()
    _WD_Navigate($WD_SESSION, $sFilePath)
    _WD_LoadWait($WD_SESSION, 1000)

    Local $sSelectElement = _WD_FindElement($WD_SESSION, $_WD_LOCATOR_ByXPath, "//select[@id='OptionToChoose']")
    Local $aOptionsList = _WD_ElementSelectAction($WD_SESSION, $sSelectElement, "options")
    Local $sCurrentValue = _WD_ElementSelectAction($WD_SESSION, $sSelectElement, "value")
    _ArrayDisplay($aOptionsList, '$aOptionsList, CurrentValue = ' & $sCurrentValue, '', 0, Default, '                          Value                          |                          Label                          ')

    Local $sValue = "1"
    _WD_ElementOptionSelect($WD_SESSION, $_WD_LOCATOR_ByXPath, "//select[@id='OptionToChoose']/option[@value='" & $sValue & "']")
    $sCurrentValue = _WD_ElementSelectAction($WD_SESSION, $sSelectElement, "value")
    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, 'Using XPath #' & @ScriptLineNumber, _
            'After selecting Value "' & $sValue & '"' & @CRLF & _
            'CurrentValue = ' & $sCurrentValue)

    $sValue = "2"
    _WD_ElementOptionSelect($WD_SESSION, $_WD_LOCATOR_ByCSSSelector, "#OptionToChoose option[value='" & $sValue & "']")
    $sCurrentValue = _WD_ElementSelectAction($WD_SESSION, $sSelectElement, "value")
    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, 'Using CSSSelector #' & @ScriptLineNumber, _
            'After selecting Value "' & $sValue & '"' & @CRLF & _
            'CurrentValue = ' & $sCurrentValue)

    Local $sText = "Moon"
    _WD_ElementOptionSelect($WD_SESSION, $_WD_LOCATOR_ByXPath, "//select[@id='OptionToChoose']/option[contains(text(), '" & $sText & "')]")
    $sCurrentValue = _WD_ElementSelectAction($WD_SESSION, $sSelectElement, "value")
    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, 'Using XPath #' & @ScriptLineNumber, _
            'After selecting Label "' & $sText & '"' & @CRLF & _
            'CurrentValue = ' & $sCurrentValue)

    ; Selecting Text with CSSSelector is not possible.
    ; https://www.w3.org/TR/selectors-3/#content-selectors
    ; https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text
    ; https://sqa.stackexchange.com/questions/362/a-way-to-match-on-text-using-css-locators

    Local $iIndex = 2 ; be aware that Index is 1-based
    _WD_ElementOptionSelect($WD_SESSION, $_WD_LOCATOR_ByXPath, "//select[@id='OptionToChoose']/option[" & $iIndex & "]")
    $sCurrentValue = _WD_ElementSelectAction($WD_SESSION, $sSelectElement, "value")
    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, 'Using XPath #' & @ScriptLineNumber, _
            'After selecting Index = ' & $iIndex & @CRLF & _
            'CurrentValue = ' & $sCurrentValue)

    $iIndex = 3 ; be aware that Index is 1-based
    _WD_ElementOptionSelect($WD_SESSION, $_WD_LOCATOR_ByCSSSelector, "select#OptionToChoose option:nth-child(" & $iIndex & ")")
    $sCurrentValue = _WD_ElementSelectAction($WD_SESSION, $sSelectElement, "value")
    MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, 'Using CSSSelector #' & @ScriptLineNumber, _
            'After selecting Index = ' & $iIndex & @CRLF & _
            'CurrentValue = ' & $sCurrentValue)

    _WD_Shutdown()
EndFunc   ;==>_Example

Func _WriteTestHtml($sFilePath = @ScriptDir & "\wd_demo_SelectElement_TestFile.html")
    FileDelete($sFilePath)
    Local Const $sHtml = _
            "<html lang='en'>" & @CRLF & _
            "    <head>" & @CRLF & _
            "        <meta charset='utf-8'>" & @CRLF & _
            "        <title>TESTING</title>" & @CRLF & _
            "    </head>" & @CRLF & _
            "    <body>" & @CRLF & _
            "       <select id='OptionToChoose'>" & @CRLF & _
            "          <option value='' selected='selected'>Choose option</option>" & @CRLF & _
            "          <option value='1'>Sun</option>" & @CRLF & _
            "          <option value='2'>Earth</option>" & @CRLF & _
            "          <option value='3'>Moon</option>" & @CRLF & _
            "       </select>" & @CRLF & _
            "    </body>" & @CRLF & _
            "</html>"
    FileWrite($sFilePath, $sHtml)
    Return "file:///" & StringReplace($sFilePath, "\", "/")
EndFunc   ;==>_WriteTestHtml

Func SetupChrome()
    _WD_Option('Driver', 'chromedriver.exe')
    _WD_Option('Port', 9515)
    _WD_Option('DriverParams', '--verbose --log-path="' & @ScriptDir & '\chrome.log"')

    _WD_Startup()

;~  Local $sCapabilities = '{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true, "excludeSwitches": [ "enable-automation"]}}}}'
    _WD_CapabilitiesStartup()
    _WD_CapabilitiesAdd('alwaysMatch', 'chrome')
    _WD_CapabilitiesAdd('w3c', True)
    _WD_CapabilitiesAdd('excludeSwitches', 'enable-automation')
    Local $sCapabilities = _WD_CapabilitiesGet()

    Local $WD_SESSION = _WD_CreateSession($sCapabilities)

    Return $WD_SESSION
EndFunc   ;==>SetupChrome

 

Edited by mLipok
script edited

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 * How to ask ChatGPT for AutoIt Codefor 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-04-24

Link to comment
Share on other sites

  • 1 month later...

Here is better example showing how to attach to firstly opened FireFox session/instance:

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

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

# TODO:
; https://github.com/operasoftware/operachromiumdriver/blob/master/docs/desktop.md   --remote-debugging-port=port

Global $_MY__WD_SESSION
Global $__g_sDownloadDir = @ScriptDir & '\Testing_Download'

_Test()

Exit

Func _Test()
    Local $s_FireFox_Binary = "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
    If $s_FireFox_Binary And FileExists($s_FireFox_Binary) = 0 Then $s_FireFox_Binary = ''

    Local $iAnswer = MsgBox($MB_YESNO + $MB_TOPMOST + $MB_ICONQUESTION + $MB_DEFBUTTON2, "Question", _
            "Open new sesion ?" & @CRLF & "[ NO ] = Try attach to active FireFox instance")
    If $iAnswer = $IDYES Then
        _Testing_CreateSession($s_FireFox_Binary)
;~      _Testing_WD_Navigate()
        Return     ; do not process next functions
    Else
        _Testing_AttachSession($s_FireFox_Binary)
        _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($s_FireFox_Binary)
    $_MY__WD_SESSION = _MY__WD_SetupFireFox(False, $__g_sDownloadDir, $s_FireFox_Binary, False)
EndFunc   ;==>_Testing_CreateSession

Func _Testing_AttachSession($s_FireFox_Binary)
    $_MY__WD_SESSION = _MY__WD_SetupFireFox(False, $__g_sDownloadDir, $s_FireFox_Binary, 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 _MY__WD_SetupFireFox($b_Headless, $s_Download_dir = Default, $s_FireFox_Binary = 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

    Local $s_Capabilities = Default
    Local $s_Profile_Dir  = @LocalAppDataDir & '\Mozilla\Firefox\Profiles\WD_Testing_Profile'
    DirCreate($s_Download_dir) ; MUST EXIST !!
    DirCreate($s_Profile_Dir) ; MUST EXIST !!

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

    #WARRNING DO NOT USE '--log-path=' BECAUSE OF   RODO / GDPR
    _WD_Option('Driver', 'geckodriver.exe')
    _WD_Option('Port', 4444)
    _WD_Option('DefaultTimeout', 1000)

    If $bTryAttach Then
        _WD_Option('DriverParams', '--log trace --marionette-port 2828 --connect-existing')
    Else
        _WD_Option('DriverParams', '--log trace --marionette-port 2828')

        _WD_CapabilitiesStartup()
        _WD_CapabilitiesAdd('alwaysMatch')
        _WD_CapabilitiesAdd('acceptInsecureCerts', True)
        _WD_CapabilitiesAdd('firstMatch', 'firefox')
        _WD_CapabilitiesAdd('args', '-profile')

        _WD_CapabilitiesAdd('args', $s_Profile_Dir) ; CHANGE TO PROPER DIRECTORY PATH
        If $s_FireFox_Binary Then _WD_CapabilitiesAdd('binary', $s_FireFox_Binary)

        If $b_Headless Then _
                _WD_CapabilitiesAdd('args', '--headless')

        _WD_CapabilitiesDump(@ScriptLineNumber & ' :WebDriver:Capabilities:')
        $s_Capabilities = _WD_CapabilitiesGet()
    EndIf

    _WD_Startup()
    If @error Then Return SetError(@error, @extended, '')

    Local $WD_SESSION = _WD_CreateSession($s_Capabilities)
    Return SetError(@error, @extended, $WD_SESSION)
EndFunc   ;==>_MY__WD_SetupFireFox

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


REMARK:
It turned out to be very useful when implementing the automation of websites for which login is required (especially with OTP send via SMS ), or in a situation where you need to repeatedly test one selected aspect of automation.

Edited by mLipok

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 * How to ask ChatGPT for AutoIt Codefor 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-04-24

Link to comment
Share on other sites

  • 4 weeks later...

@mLipok first thank you for posting your Firstly open FireFox example.

Do you know of or have an example of connecting to an existing MSEdge browser session?

I'm trying to modify your example of connecting to FireFox to work with Edge.

I am realizing just how little I know.

Thank you

 

Link to comment
Share on other sites

  • 1 month later...

I'm having a terrible time getting started with Web Driver.  I've tried both of the GDPR examples and get errors including several "undefined function" errors.  Errors listed below.  Am I missing some includes?  I'm baffled.

 

"C:\Users\psiess\Downloads\GDPR fines (2).au3"(74,73) : error: _WD_GetTable() called with wrong number of args.
        $aResult = _WD_GetTable($sSession, "//table[@id='penalties']", $iPage)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_helper.au3"(2023,44) : REF: definition of _WD_GetTable().
Func _WD_GetTable($sSession, $sBaseElement)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Users\psiess\Downloads\GDPR fines (2).au3"(118,52) : error: _WD_GetTable() already defined.
Func _WD_GetTable($sSession, $sBaseElement, $iPage)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_core.au3"(231,41) : error: Json_Decode(): undefined function.
        Local $oJSON = Json_Decode($sResponse)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_core.au3"(232,53) : error: Json_Get(): undefined function.
        $sSession = Json_Get($oJSON, "[value][sessionId]")
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_core.au3"(1250,38) : error: __WinHttpVer(): undefined function.
        Local $sWinHttpVer = __WinHttpVer()
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_helper.au3"(592,29) : error: Json_IsObject(): undefined function.
        If Json_IsObject($sValue) =
        ~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_helper.au3"(593,38) : error: Json_ObjGetKeys(): undefined function.
            $asJSON = Json_ObjGetKeys($sValue)
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_helper.au3"(2259,33) : error: Json_ObjCreate(): undefined function.
    Local $vData = Json_ObjCreate()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_helper.au3"(2260,34) : error: Json_Put(): undefined function.
    Json_Put($vData, '.type', 'key')
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Program Files (x86)\AutoIt3\Include\wd_helper.au3"(2264,36) : error: Json_Encode(): undefined function.
    Local $sJSON = Json_Encode($vData)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

Link to comment
Share on other sites

16 minutes ago, Danp2 said:

Hi @PaulS,

I would recommend that you read the Getting Started section of the ReadMe document, which shows the additional UDFs (some required; some optional) that need to be installed.

HTH,

Dan

Thanks Dan.  I had already followed the installation instructions, but went back and confirmed that I have all of the prerequisites in place.  I'm now trying wd_demo.au3, and running in to undeclared variable errors in wd_capabilities.au3.  For example:  warning: $Json_UNQUOTED_STRING: possibly used before declaration

 

Link to comment
Share on other sites

I will have a look what goes wrong with the GDPR example after my vacation. 

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

49 minutes ago, PaulS said:

$Json_UNQUOTED_STRING:

This const is defined in json.au3, so there is something incorrect with your setup. I would start by checking to see if maybe there is another copy of json.au3 somewhere that is interfering. FWIW, this is the header from my copy of json.au3 --

; ============================================================================================================================
; File      : Json.au3 (2021.11.20)
; Purpose   : A Non-Strict JavaScript Object Notation (JSON) Parser UDF
; Author    : Ward
; Dependency: BinaryCall.au3
; Website   : http://www.json.org/index.html
;
; Source    : jsmn.c
; Author    : zserge
; Website   : http://zserge.com/jsmn.html
;
; Source    : json_string_encode.c, json_string_decode.c
; Author    : Ward
;             Jos - Added Json_Dump()
;             TheXMan - Json_ObjGetItems and some Json_Dump Fixes.
;             Jos - Changed Json_ObjGet() and Json_ObjExists() to allow for multilevel object in string.
; ============================================================================================================================

 

Link to comment
Share on other sites

Create an account or sign in to comment

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

Create an account

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

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...