This commit is contained in:
louiscklaw
2025-01-31 19:27:58 +08:00
parent 9476a736d3
commit ce9a4aa9b3
313 changed files with 6340 additions and 0 deletions

1
armandarmand/task1/.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
*.zip filter=lfs diff=lfs merge=lfs -text

View File

@@ -0,0 +1,5 @@
Option Explicit
Sub helloworld()
Worksheets ("Sheet1")
End Sub

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,3 @@
rmdir *.bas
xlwings vba edit --file .\main.xlsm

Binary file not shown.

View File

@@ -0,0 +1,3 @@
# client working directory
C:\Users\user\OneDrive\Desktop\delivery

View File

@@ -0,0 +1,15 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = false
[*.md]
trim_trailing_whitespace = false

View File

@@ -0,0 +1,3 @@
node_modules
**/~*
*.del

View File

@@ -0,0 +1,18 @@
{
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "strict",
"insertPragma": false,
"jsxBracketSameLine": false,
"jsxSingleQuote": false,
"printWidth": 120,
"proseWrap": "preserve",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": false,
"overrides": []
}

View File

@@ -0,0 +1,5 @@
@REM start excel by yourself
@REM ./test.xlsm
xlwings vba edit --file ./test.xlsm

View File

@@ -0,0 +1,5 @@
@REM start excel by yourself
@REM ./test.xlsm
xlwings vba edit --file ./test.xlsm

View File

@@ -0,0 +1,537 @@
Private Sub Workbook_Open()
'Opens the VBA Editor
'Call Open_VBA_Editor
End Sub
Private Sub Open_VBA_Editor()
Application.CommandBars.FindControl(ID:=1695).Execute
End Sub

View File

@@ -0,0 +1,63 @@
Attribute VB_Name = "browsers_all"
' This module contains examples on how to work
' with a specific browser.
'
Private Sub Use_Chrome()
Dim driver As New ChromeDriver
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_Firefox()
Dim driver As New ChromeDriver
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_Opera()
Dim driver As New OperaDriver
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_InternetExplorer()
Dim driver As New IEDriver
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_PhantomJS()
Dim driver As New PhantomJSDriver
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_FirefoxLight()
' Firefox Light:
' http://sourceforge.net/projects/lightfirefox/
Dim driver As New ChromeDriver
driver.SetBinary "C:\...\light.exe"
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_CEF()
' Chromium Embedded Framework:
' https://cefbuilds.com
Dim driver As New ChromeDriver
driver.SetBinary "C:\...\cefclient.exe"
driver.AddArgument "url=data:,"
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub

View File

@@ -0,0 +1,40 @@
Attribute VB_Name = "browsers_debug"
' This module contains examples on how to work with
' a Chrome based browser that was launched with a
' listening debug port.
'
Private Sub Connect_To_Chrome()
'Use this command line to launch the browser:
'chrome.exe -remote-debugging-port=9222
Dim driver As New ChromeDriver
driver.SetCapability "debuggerAddress", "127.0.0.1:9222"
driver.Get "https://en.wikipedia.org"
driver.Quit
End Sub
Private Sub Connect_To_CFE()
'Chromium Embedded Framework: https://cefbuilds.com/
'Use this command line to launch the browser:
'cefclient.exe -remote-debugging-port=9333 -url=data:,
Dim driver As New ChromeDriver
driver.SetCapability "debuggerAddress", "127.0.0.1:9333"
driver.Get "https://en.wikipedia.org"
driver.Quit
End Sub
Private Sub Connect_To_Firefox()
'Firefox must have the WebDriver extension installed:
'%USERPROFILE%\AppData\Local\SeleniumBasic\ChromeDriver.xpi
'To use another port, set the preference webdriver_firefox_port in about:config
Dim driver As New ChromeDriver
driver.SetCapability "debuggerAddress", "127.0.0.1:7055"
driver.Get "https://en.wikipedia.org"
End Sub

View File

@@ -0,0 +1,33 @@
Attribute VB_Name = "browsers_extension"
' This module contains examples on how to work with
' an extension.
'
Private Sub Use_Chrome_With_Extension()
' To download an extension:
' http://chrome-extension-downloader.com
' To manage the extension preferences:
' Developper Tools > Resources > Local Storage > chrome-extension://...
Dim driver As New ChromeDriver
driver.AddExtension "C:\Users\florent\Downloads\Personal-Blocklist-(by-Google)_v2.6.1.crx"
driver.SetPreference "plugins.plugins_disabled", Array("Adobe Flash Player")
driver.Get "chrome-extension://nolijncfnkgaikbjbdaogikpmpbdcdef/manager.html"
driver.ExecuteScript "localStorage.setItem('blocklist', '[""wikipedia.org""]');"
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_Firefox_With_Extension()
' To download an extension, use a browser other than Firefox
Dim driver As New ChromeDriver
driver.AddExtension "C:\Users\florent\Downloads\firebug-2.0.12-fx.xpi"
driver.SetPreference "extensions.firebug.showFirstRunPage", False
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub

View File

@@ -0,0 +1,52 @@
Attribute VB_Name = "browsers_profile"
' This module contains examples on how to work with
' a customized profile.
'
Private Sub Use_Chrome_With_Custom_profile_name()
' Profiles folder : %APPDATA%\Google\Chrome\Profiles
' Note that with Chrome the profile is always persistant
Dim driver As New ChromeDriver
driver.SetProfile "Selenium"
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_Chrome_With_Custom_profile_path()
' Default profile : %LOCALAPPDATA%\Google\Chrome\User Data
' Profiles folder : %APPDATA%\Google\Chrome\Profiles
' Note that with Chrome the profile is always persistant
Dim driver As New ChromeDriver
driver.SetProfile "%LOCALAPPDATA%\Google\Chrome\User Data"
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_Firefox_With_Custom_profile_name()
' To manage firefox profiles: firefox -p
' Profiles folder: %APPDATA%\Mozilla\Firefox\Profiles
' When persistant is False, the driver works with a copy in the Temp folder.
Dim driver As New ChromeDriver
driver.SetProfile "Selenium", persistant:=True
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub
Private Sub Use_Firefox_With_Custom_profile_path()
' To manage the profiles: firefox -p
' Profiles folder: %APPDATA%\Mozilla\Firefox\Profiles
' When persistant is False, the driver works with a copy in the Temp folder.
Dim driver As New ChromeDriver
driver.SetProfile "%APPDATA%\Mozilla\Firefox\Profiles\kfvj49h4.Selenium", persistant:=True
driver.Get "https://www.google.co.uk"
driver.Quit
End Sub

View File

@@ -0,0 +1,25 @@
Attribute VB_Name = "browsers_remote"
' This module contains examples on how to work with
' a browser installed on another station.
'
' Selenium Standalone Server:
' http://www.seleniumhq.org/download/
'
' Command line to start the server:
' java -jar selenium-server-standalone-2.47.1.jar
'
Const SERVER = "http://127.0.0.1:4444/wd/hub"
Private Sub Take_ScreenShot_Remotely()
Dim driver As New WebDriver
driver.StartRemotely SERVER, "safari"
'open the page with the URL in Sheet3 in cell A2
driver.Get [Sheet3!A4]
'Take the screenshoot
driver.TakeScreenshot().ToExcel [Sheet3!A7]
driver.Quit
End Sub

View File

@@ -0,0 +1,17 @@
Attribute VB_Name = "browsers_running"
' This module shows how to work with a running instance of
' a driver by using the GetObject function.
'
' To do so, create a vbs file with the following code and run it.
'
' Set driver = CreateObject("Selenium.ChromeDriver")
' driver.Start
' WScript.Echo "Click OK to quit"
'
Public Sub OpenURL()
Dim driver As WebDriver
Set driver = GetObject("Selenium.WebDriver")
driver.Get "https://www.google.co.uk"
End Sub

View File

@@ -0,0 +1,30 @@
Attribute VB_Name = "browsers_static"
' This module contains is an example on how to use
' the same instance of a browser with different
' procedures.
'
Private driver As New Selenium.ChromeDriver
Private Assert As New Selenium.Assert
Private Verify As New Selenium.Verify
Private Waiter As New Selenium.Waiter
Private utils As New Selenium.utils
Private Keys As New Selenium.Keys
Private By As New Selenium.By
Public Sub NavigateToURL1()
driver.Get [Sheet4!B2]
End Sub
Public Sub NavigateToURL2()
driver.Get [Sheet4!B5]
End Sub
Public Sub QuitDriver()
driver.Quit
Set driver = Nothing
End Sub

View File

@@ -0,0 +1,5 @@
@REM start excel by yourself
@REM ./test.xlsm
xlwings vba edit --file ./Examples.xlsm

View File

@@ -0,0 +1,36 @@
Attribute VB_Name = "example_amazon"
Const css_input = "#twotabsearchtextbox"
Const css_spinner = "#centerBelowPlusspacer"
Const css_titles = "#s-results-list-atf a.s-access-detail-page"
Const css_bt_next = "#pagnNextLink #pagnNextString"
Private Sub Search_Amazon()
Const search_input = "drum carrot"
Dim driver As New ChromeDriver
driver.Get "http://www.amazon.com/s"
' type in the field and submit
driver.FindElementByCss(css_input) _
.SendKeys(search_input) _
.Submit
Dim By As New By
Do
' wait for the loading bar to disapear
driver.WaitNotElement By.css(css_spinner), 7000
' handle results
For Each ele In driver.FindElementsByCss(css_titles)
Debug.Print ele.Text
Next
' click next page or exit the loop if the link is not present
Set bt_next = driver.FindElementByCss(css_bt_next, timeout:=0, Raise:=False)
If bt_next Is Nothing Then _
Exit Do
bt_next.Click
Loop
End Sub

View File

@@ -0,0 +1,33 @@
Attribute VB_Name = "usage_alert"
Private Assert As New Selenium.Assert
Private Sub Handle_Alerts()
Dim driver As New ChromeDriver
driver.SetCapability "unexpectedAlertBehaviour", "ignore"
driver.Get "http://the-internet.herokuapp.com/javascript_alerts"
' Display alert
driver.FindElementByCss("#content li:nth-child(2) button").Click
' Set the context on the alert dialog
Set dlg = driver.SwitchToAlert(Raise:=False)
' Assert an alert is present and the message
Assert.False dlg Is Nothing, "No alert present!"
Assert.Equals "I am a JS Confirm", dlg.Text
' Close alert
dlg.Accept
driver.Quit
End Sub
'Returns true if an alert is present, false otherwise
' driver: web driver
Private Function IsDialogPresent(driver As WebDriver) As Boolean
On Error Resume Next
T = driver.title
IsDialogPresent = (26 = Err.Number)
End Function

View File

@@ -0,0 +1,68 @@
Attribute VB_Name = "usage_authentication"
Private Assert As New Selenium.Assert
Private Sub Basic_Authentication_In_URL()
Dim driver As New IEDriver
driver.Get "http://admin:admin@the-internet.herokuapp.com/basic_auth"
txt = driver.FindElementByCss(".example p").Text
Assert.Matches "^Congratulations!", txt
driver.Quit
End Sub
Private Sub AuthenticationDialog_Selenium()
Dim driver As New IEDriver
driver.Get "http://the-internet.herokuapp.com/basic_auth"
Dim dlg As Alert: Set dlg = driver.SwitchToAlert(Raise:=False)
If Not dlg Is Nothing Then
dlg.SetCredentials "admin", "admin"
dlg.Accept
End If
txt = driver.FindElementByCss(".example p").Text
Assert.Matches "^Congratulations!", txt
driver.Quit
End Sub
Private Sub AuthenticationDialog_WScript()
Dim driver As New IEDriver
driver.Get "http://the-internet.herokuapp.com/basic_auth"
Dim dlg As Alert: Set dlg = driver.SwitchToAlert(Raise:=False)
If Not dlg Is Nothing Then
Set wsh = CreateObject("WScript.Shell")
wsh.SendKeys "admin"
wsh.SendKeys "{TAB}"
wsh.SendKeys "admin"
dlg.Accept
End If
txt = driver.FindElementByCss(".example p").Text
Assert.Matches "^Congratulations!", txt
driver.Quit
End Sub
Private Sub AuthenticationDialog_AutoIt()
Dim driver As New IEDriver
driver.Get "http://the-internet.herokuapp.com/basic_auth"
Dim dlg As Alert: Set dlg = driver.SwitchToAlert(Raise:=False)
If Not dlg Is Nothing Then
Set aut = CreateObject("AutoItX3.Control")
aut.Send "admin"
aut.Send "{TAB}"
aut.Send "admin"
dlg.Accept
End If
txt = driver.FindElementByCss(".example p").Text
Assert.Matches "^Congratulations!", txt
driver.Quit
End Sub

View File

@@ -0,0 +1,22 @@
Attribute VB_Name = "usage_checkbox"
Private Assert As New Selenium.Assert
Private Sub Handle_Checkbox()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/checkboxes"
'Get the 2 second checkbox
Dim cs As WebElement
Set cb = driver.FindElementByCss("#checkboxes input:nth-of-type(2)")
'Assert the checkbox is checked
Assert.True cb.IsSelected
'Uncheck the checkbox
cb.Click
'Assert the checkbox is unchecked
Assert.False cb.IsSelected
driver.Quit
End Sub

View File

@@ -0,0 +1,14 @@
Attribute VB_Name = "usage_clipboard"
Dim Keys As New Selenium.Keys
Private Sub Paste_ClipBoard()
Dim driver As New Selenium.ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
driver.SetClipBoard [b3]
driver.FindElementById("searchInput").SendKeys Keys.Control, "v"
Debug.Assert 0
driver.Quit
End Sub

View File

@@ -0,0 +1,17 @@
Attribute VB_Name = "usage_cookies"
Private Assert As New Selenium.Assert
Private Sub Handle_Cookies()
Dim driver As New ChromeDriver
driver.Get "http://admin:admin@the-internet.herokuapp.com/download_secure"
'Get a cookie by name
Dim cookie As cookie
Set cookie = driver.Manage.FindCookieByName("rack.session")
Assert.Equals "the-internet.herokuapp.com", cookie.Domain
'Stop the browser
driver.Quit
End Sub

View File

@@ -0,0 +1,28 @@
Attribute VB_Name = "usage_dom"
Private Sub Get_DOM_1()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Dim html As Object
Set html = CreateObject("htmlfile")
html.Open
html.Write driver.PageSource()
html.Close
Debug.Print html.body.innerText
driver.Quit
End Sub
Private Sub Get_DOM_2()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Dim html As Object
Set html = CreateObject("htmlfile")
html.body.innerHTML = driver.ExecuteScript("return document.body.innerHTML;")
Debug.Print html.body.innerText
driver.Quit
End Sub

View File

@@ -0,0 +1,378 @@
Attribute VB_Name = "usage_download"
Private Declare PtrSafe Function FindWindowExA Lib "user32.dll" ( _
ByVal hwndParent As LongPtr, _
ByVal hwndChildAfter As LongPtr, _
ByVal lpszClass As String, _
ByVal lpszWindow As String) As Long
Private Declare PtrSafe Function PostMessageA Lib "user32.dll" ( _
ByVal hwnd As LongPtr, _
ByVal wMsg As LongPtr, _
ByVal wParam As LongPtr, _
ByVal lParama As LongPtr) As Long
Private Declare PtrSafe Function GetWindowLongA Lib "user32.dll" ( _
ByVal hwnd As LongPtr, ByVal nIndex As Integer) As Long
Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc.dll" ( _
ByVal hwnd As LongPtr, _
ByVal dwId As Long, _
ByRef riid As Any, _
ByRef ppvObject As IAccessible) As Long
Private Declare PtrSafe Function AccessibleChildren Lib "oleacc.dll" ( _
ByVal paccContainer As IAccessible, _
ByVal iChildStart As Long, _
ByVal cChildren As Long, _
ByRef rgvarChildren As Variant, _
ByRef pcObtained As Long) As Long
''
' Downloads the link defined in the href attribute of a web element
''
Private Sub Usage_Download_StaticLink()
Dim driver As New IEDriver, ele As WebElement
driver.Get "https://www.mozilla.org/en-US/foundation/documents"
Set ele = driver.FindElementByLinkText("IRS Form 872-C")
Download_StaticLink ele, ThisWorkbook.Path & "\irs-form-872-c_1.pdf"
driver.Quit
End Sub
''
' Downloads a file with IE and waits for completion
''
Private Sub Download_File_IE()
Dim driver As New IEDriver, ele As WebElement
driver.Get "https://www.mozilla.org/en-US/foundation/documents"
Dim filePath As String
driver.FindElementByLinkText("IRS Form 872-C").ExecuteScript "this.click()"
filePath = DownloadFileSyncIE(ThisWorkbook.Path)
driver.Quit
End Sub
''
' Downloads a file with IE without waiting for completion
''
Private Sub Download_File_Asynchrone_IE()
Dim driver As New IEDriver, ele As WebElement
driver.Get "https://www.mozilla.org/en-US/foundation/documents"
' Init the file waiter
WaitNewFile ThisWorkbook.Path & "\*.pdf"
driver.FindElementByLinkText("IRS Form 872-C").ExecuteScript "this.click()"
DownloadFileAsyncIE ThisWorkbook.Path
' Waits for a new file
file = WaitNewFile()
Debug.Assert 0
driver.Quit
End Sub
''
' Sets the download folder with Firefox
''
Private Sub Download_File_Firefox()
Dim driver As New ChromeDriver, file As String
'Set the preferences specific to Firefox
driver.SetPreference "browser.download.folderList", 2
driver.SetPreference "browser.download.dir", ThisWorkbook.Path
driver.SetPreference "browser.helperApps.neverAsk.saveToDisk", "application/pdf"
driver.SetPreference "pdfjs.disabled", True
' Init the file waiter
WaitNewFile ThisWorkbook.Path & "\*.pdf"
' Open the file for download
driver.Get "https://www.mozilla.org/en-US/foundation/documents"
driver.FindElementByLinkText("IRS Form 872-C").Click
' Waits for a new file
file = WaitNewFile()
'Stop the browser
driver.Quit
End Sub
''
' Sets the download folder with Chrome
''
Private Sub Download_File_Chrome()
Dim driver As New ChromeDriver, file As String
'Set the preferences specific to Chrome
driver.SetPreference "download.default_directory", ThisWorkbook.Path
driver.SetPreference "download.directory_upgrade", True
driver.SetPreference "download.prompt_for_download", False
driver.SetPreference "plugins.plugins_disabled", Array("Chrome PDF Viewer")
' Init the file waiter
WaitNewFile ThisWorkbook.Path & "\*.pdf"
'Open the file for download
driver.Get "https://www.mozilla.org/en-US/foundation/documents"
driver.FindElementByLinkText("IRS Form 872-C").Click
' Waits for a new file
file = WaitNewFile()
'Stop the browser
Debug.Assert 0
driver.Quit
End Sub
' ### HELPERS FUNCTIONS ###
''
' Saves the file pointed by the href attribute : <a href="/doc.pdf">Document</a>
' @element {WebElement} Web element with the href link
' @save_as {String} Path were the file is to be saved
''
Private Sub Download_StaticLink(element As WebElement, save_as As String)
' Extract the data to build the request (link, user-agent, language, cookie)
Dim info As Selenium.Dictionary
Set info = element.ExecuteScript("return {" & _
"link: this.href," & _
"agent: navigator.userAgent," & _
"lang: navigator.userLanguage," & _
"cookie: document.cookie };")
' Send the request
Static xhr As Object
If xhr Is Nothing Then Set xhr = CreateObject("Msxml2.ServerXMLHTTP.6.0")
xhr.Open "GET", info("link")
xhr.setRequestHeader "User-Agent", info("agent")
xhr.setRequestHeader "Accept-Language", info("lang")
xhr.setRequestHeader "Cookie", info("cookie")
xhr.Send
If (xhr.Status \ 100) - 2 Then Err.Raise 5, , xhr.Status & " " & xhr.StatusText
' Save the response to a file
Static bin As Object
If bin Is Nothing Then Set bin = CreateObject("ADODB.Stream")
If Len(Dir$(save_as)) Then Kill save_as
bin.Open
bin.Type = 1
bin.Write xhr.ResponseBody
bin.Position = 0
bin.SaveToFile save_as
bin.Close
End Sub
''
' Waits for a new file to be created in a folder
' @folder {String} Folder where the file will be created
' Usage:
' WaitNewFile "C:\download\*.pdf"
' ' The new file is created here
' filename = WaitNewFile()
''
Public Function WaitNewFile(Optional target As String) As String
Static files As Collection, filter$
Dim file$, file_path$, i&
If Len(target) Then
' Initialize the list of files and return
filter = target
Set files = New Collection
file = Dir(filter, vbNormal)
Do While Len(file)
files.Add Empty, file
file = Dir
Loop
Exit Function
End If
' Waits for a file that is not in the list
On Error GoTo WaitReady
Do
file = Dir(filter, vbNormal)
Do While Len(file)
files.Item file
file = Dir
Loop
For i = 0 To 3000: DoEvents: Next
Loop
WaitReady:
' Waits for the size to be superior to 0 and try to rename it
file_path = Left$(filter, InStrRev(filter, "\")) & file
Do
If FileLen(file_path) Then
On Error Resume Next
Name file_path As file_path
If Err = 0 Then Exit Do
End If
For i = 0 To 3000: DoEvents: Next
Loop
files.Add Empty, file
WaitNewFile = file_path
End Function
''
' Saves the file from the download dialogue, waits for completion and returns the path
' @save_as: folder or file path
''
Private Function DownloadFileSyncIE(ByVal save_as As String) As String
Const dl_key = "HKCU\Software\Microsoft\Internet Explorer\Main\Default Download Directory"
Static shl As Object, Waiter As New Waiter
If shl Is Nothing Then
Set shl = CreateObject("WScript.Shell")
shl.RegWrite "HKCU\Software\Microsoft\Internet Explorer\Main\NotifyDownloadComplete", "no", "REG_SZ"
shl.RegWrite "HKCU\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_RESTRICT_FILEDOWNLOAD\iexplore.exe", 0, "REG_DWORD"
End If
Dim ie_hwnd, frm_hwnd, endtime#, i&, n&, folder_bak$, file_name$
' wait for the download dialogue (IEFrame/Frame Notification Bar/DirectUIHWND)
ie_hwnd = FindWindowExA(0, 0, "IEFrame", vbNullString)
endtime = Now + 5000 / 86400#
Do
frm_hwnd = FindWindowExA(ie_hwnd, 0, "Frame Notification Bar", vbNullString)
If frm_hwnd Then
If GetWindowLongA(frm_hwnd, -16) And &H10000000 Then Exit Do ' If visible
End If
If Now > endtime Then Err.Raise 5, , "Failed to find the download dialog"
Waiter.Wait 100
Loop
' save the download folder path and create a temporary folder
tmp_dir = Environ$("TEMP") & "\dl-ie-4f521"
On Error Resume Next
folder_bak = shl.RegRead(dl_key)
MkDir tmp_dir
Kill tmp_dir & "\*"
On Error GoTo 0
' set the download folder in the registry
shl.RegWrite dl_key, tmp_dir, "REG_SZ"
' send the shortcut for Save (Alt + S)
Waiter.Wait 500
PostMessageA ie_hwnd, &H104&, &H12, &H20000001 'WM_SYSKEYDOWN, VK_MENU
PostMessageA ie_hwnd, &H104&, &H53, &H20000001 'WM_SYSKEYDOWN, S
PostMessageA ie_hwnd, &H105&, &H53, &HC0000001 'WM_SYSKEYUP, S
PostMessageA ie_hwnd, &H101&, &H12, &HC0000001 'WM_KEYUP, VK_MENU
' wait for the file to be downloaded
Do
Waiter.Wait 100
file_name = VBA.Dir$(tmp_dir & "\*")
Loop While InStr(Len(file_name) - 8, file_name, ".partial") Or Len(file_name) = 0
' restore the download folder in the registry
If folder_bak = Empty Then
shl.RegDelete dl_key
Else
shl.RegWrite dl_key, folder_bak, "REG_SZ"
End If
' delete existing file
If Len(VBA.Dir$(save_as, vbNormal)) Then Kill save_as
If Len(VBA.Dir$(save_as, vbDirectory)) Then
save_as = save_as & "\" & file_name
If Len(VBA.Dir$(save_as, vbNormal)) Then Kill save_as
End If
' move the file to the provided path
Name tmp_dir & "\" & file_name As save_as
DownloadFileSyncIE = save_as
End Function
''
' Saves the file from the download dialogue without waiting for completion
' @folder: download folder
''
Private Sub DownloadFileAsyncIE(folder As String)
Const timeout = 5000, bt_save = "Save", bt_close = "Close"
Const dl_key = "HKCU\Software\Microsoft\Internet Explorer\Main\Default Download Directory"
Static shl As Object, Waiter As New Waiter
If shl Is Nothing Then
Set shl = CreateObject("WScript.Shell")
shl.RegWrite "HKCU\Software\Microsoft\Internet Explorer\Main\NotifyDownloadComplete", "no", "REG_SZ"
shl.RegWrite "HKCU\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_RESTRICT_FILEDOWNLOAD\iexplore.exe", 0, "REG_DWORD"
End If
' wait for the download dialog (IEFrame/Frame Notification Bar/DirectUIHWND)
Dim ie_hwnd, frm_hwnd, dlg_hwnd, endtime#, folder_bak$, i&
ie_hwnd = FindWindowExA(0, 0, "IEFrame", vbNullString)
endtime = Now + timeout / 86400#
Do
frm_hwnd = FindWindowExA(ie_hwnd, 0, "Frame Notification Bar", vbNullString)
If frm_hwnd Then
If GetWindowLongA(frm_hwnd, -16) And &H10000000 Then Exit Do ' If visible
End If
If Now > endtime Then Err.Raise 5, , "Failed to find the download dialog"
For i = 1 To 5000: DoEvents: Next
Loop
' get the save button
Dim acc As IAccessible, bt As IAccessible
dlg_hwnd = FindWindowExA(frm_hwnd, 0, "DirectUIHWND", vbNullString)
Set acc = acc_from_window(dlg_hwnd)
Set bt = acc_find_button(acc, bt_save)
If bt Is Nothing Then Err.Raise 5, , "Failed to find the Save button"
' save and set the download folder in the registry
On Error Resume Next
folder_bak = shl.RegRead(dl_key)
On Error GoTo 0
shl.RegWrite dl_key, folder, "REG_SZ"
' click on Save
Waiter.Wait 500
bt.accDoDefaultAction 0&
Waiter.Wait 100
' restore the download folder in the registry
If folder_bak = Empty Then
shl.RegDelete dl_key
Else
shl.RegWrite dl_key, folder_bak, "REG_SZ"
End If
End Sub
Private Function acc_from_window(hwnd) As IAccessible
Dim iid&(0 To 3)
iid(0) = &H618736E0 ' IAccessible interface
iid(1) = &H11CF3C3D
iid(2) = &HAA000C81
iid(3) = &H719B3800
AccessibleObjectFromWindow hwnd, 0&, iid(0), acc_from_window
End Function
Private Function acc_find_button(ByVal acc As IAccessible, name$) As IAccessible
If acc.accName(0&) Like name Then
Set acc_find_button = acc
ElseIf acc.accChildCount > 0 Then
Dim children(0 To 20), count&, i&
AccessibleChildren acc, 0, acc.accChildCount, children(0), count
For i = 0 To count - 1
If VBA.IsObject(children(i)) Then
Set acc_find_button = acc_find_button(children(i), name)
If Not acc_find_button Is Nothing Then Exit For
End If
Next
End If
End Function

View File

@@ -0,0 +1,106 @@
Attribute VB_Name = "usage_dragdrop"
Private Assert As New Selenium.Assert
Private Keys As New Selenium.Keys
Private By As New Selenium.By
Private Sub Perform_DragAndDrop_HTML5()
Dim driver As New ChromeDriver
driver.Get "http://html5demos.com/drag"
Dim ele_source As WebElement, ele_target As WebElement
Set ele_source = driver.FindElementById("two")
Set ele_target = driver.FindElementById("bin")
driver.Actions.ClickAndHold(ele_source).MoveToElement(ele_target).Release.Perform
driver.Actions.DragAndDrop(ele_source, ele_target).Perform
Assert.True ele_source.IsPresent
DragAndDropHTML5 ele_source, ele_target
Assert.False ele_source.IsPresent
driver.Quit
End Sub
Private Sub Perform_DropText_HTML5()
Dim driver As New ChromeDriver
driver.Get "http://html5demos.com/drag-anything"
Const DROP_TYPE = "text/message"
Dim ele_drop As WebElement
Set ele_drop = driver.FindElementById("drop")
DropDataHTML5 ele_drop, DROP_TYPE, "my text"
Assert.Equals "my text", ele_drop.Text
driver.Quit
End Sub
Private Sub Perform_DropFile_HTML5()
Dim driver As New ChromeDriver
driver.Get "http://html5demos.com/file-api"
Dim ele_drop As WebElement
Set ele_drop = driver.FindElementById("holder")
DropFileHTML5 ele_drop, "file:///C:/Untitled.png"
driver.Quit
End Sub
' ### HELPERS FUNCTIONS ###
''
' Drop data on an element that implements HTML5 drop
' @target: web element that will receive the data
' @dataType: type of data
' @data: data to drop on the target
''
Private Sub DropDataHTML5(target As WebElement, dataType As String, data)
Const JS_DropText As String = _
"var t=this,m=arguments[0],v=arguments[1],d={dropEffect:'',types:[m],getData:funct" & _
"ion(k){return v;}},f=function(e,k){var u=document.createEvent('Event');u.initEven" & _
"t(k,1,1);u.dataTransfer=d;e.dispatchEvent(u);};f(t,'dragenter');f(t,'dragover');f" & _
"(t,'drop');"
target.ExecuteScript JS_DropText, Array(dataType, data)
End Sub
''
' Perform a drag and drop on elements that implement HTML5 drag an drop
' @source web element to drag
' @target: web element to drop on
''
Private Sub DragAndDropHTML5(source As WebElement, target As WebElement)
Const JS_DnD As String = _
"var s=this,t=arguments[0],d={dropEffect:'',types:[],setData:function(k,v){this[k]=" & _
"v;types.append(k);},getData:function(k){return this[k]}},f=function(e,k){var u=doc" & _
"ument.createEvent('Event');u.initEvent(k,1,1);u.dataTransfer=d;e.dispatchEvent(u);" & _
"};f(s,'dragstart');f(t,'dragenter');f(t,'dragover');f(t,'drop');f(s,'dragend');"
source.ExecuteScript JS_DnD, target
End Sub
''
' Perform a drag and drop on elements that implement HTML5 drag an drop
' @target: web element that will receive the file
' @filepath: file path
''
Private Sub DropFileHTML5(target As WebElement, filePath As String)
Const JS_NewInput = _
"var e=document.createElement('input');e.type='file';" & _
"document.body.appendChild(e);return e;"
Const JS_DropFile = _
"var s=this,t=arguments[0],d={dropEffect:'',files:s.files},f=function(e,k){u=docum" & _
"ent.createEvent('Event');u.initEvent(k,1,1);u.dataTransfer=d;e.dispatchEvent(u);}" & _
";f(t,'dragenter');f(t,'dragover');f(t,'drop');"
Dim source As WebElement
Set source = target.ExecuteScript(JS_NewInput)
source.SendKeys filePath
source.ExecuteScript JS_DropFile, target
End Sub

View File

@@ -0,0 +1,75 @@
Attribute VB_Name = "usage_excel"
' This module contains examples to read and write
' data from and to an excel sheet.
'
Private Table As New Selenium.Table
Private Assert As New Selenium.Assert
Private Verify As New Selenium.Verify
Private Keys As New Selenium.Keys
Private Sub Use_Cell_text()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
'get the input box
Dim ele As WebElement
Set ele = driver.FindElementById("searchInput")
'Search the text from the cell A3
ele.SendKeys [b3]
ele.Submit
driver.Quit
End Sub
Public Sub VerifyTitles()
Dim driver As New ChromeDriver
driver.setBinary "C:\tools\chrome-win\chrome.exe"
Dim row
For Each row In Table.From([Sheet1!A3]).Where("Id > 0")
'open the page with the link in column "Link"
driver.Get row("Link")
'Verify the title and set the result in column "Result"
row("Result") = Verify.Equals(row("ExpectedTitle"), driver.title)
Next
driver.Quit
End Sub
Public Sub ListLinks()
Dim driver As New ChromeDriver
'open the page with the URL in cell A2
driver.Get [Sheet2!A4]
'get all the href attributes
Dim links As List
Set links = driver.FindElementsByTag("a").Attribute("href")
links.Distinct
links.Sort
'writes the href values in cell A7
links.ToExcel [Sheet2!A7]
driver.Quit
End Sub
Public Sub TakeScreenShoot()
Dim driver As New ChromeDriver
'open the page with the URL in cell A4
driver.Get [Sheet3!A4]
'Take the screenshoot in cell A7
driver.TakeScreenshot().ToExcel [Sheet3!A7]
driver.Quit
End Sub

View File

@@ -0,0 +1,65 @@
Attribute VB_Name = "usage_find"
Private Assert As New Selenium.Assert
Private Sub Find_By_LinkText()
Dim drv As New ChromeDriver
drv.Get "https://en.wikipedia.org/wiki/Main_Page"
drv.FindElementByLinkText("Talk").Click
Assert.Matches "User talk.*", drv.title
drv.Quit
End Sub
Private Sub Find_By_Value()
Dim drv As New ChromeDriver
drv.Get "https://www.google.co.uk"
Dim ele As WebElement
Set ele = drv.FindElementByXPath("//input[@value='Google Search']")
Assert.Equals "Google Search", ele.Value
drv.Quit
End Sub
Private Sub Find_By_Partial_Value()
Dim drv As New ChromeDriver
drv.Get "https://www.google.co.uk"
Dim ele As WebElement
Set ele = drv.FindElementByXPath("//input[contains(@value,'Search')]")
Assert.Equals "Google Search", ele.Value
drv.Quit
End Sub
Private Sub Find_By_Text()
Dim drv As New ChromeDriver
drv.Get "https://www.google.co.uk"
If drv.FindElementsByXPath("//*[contains(text(),'Google')]").count Then
Debug.Print "Text is present"
Else
Debug.Print "Text is not present"
End If
drv.Quit
End Sub
Private Sub Text_Exists()
Const JS_HAS_TEXT = "return document.body.textContent.indexOf(arguments[0]) > -1"
Dim drv As New ChromeDriver
drv.Get "https://www.google.co.uk"
If drv.ExecuteScript(JS_HAS_TEXT, "Google") Then
Debug.Print "Text is present"
Else
Debug.Print "Text is not present"
End If
drv.Quit
End Sub

View File

@@ -0,0 +1,24 @@
Attribute VB_Name = "usage_frame"
Private Assert As New Selenium.Assert
Private Keys As New Selenium.Keys
Private Sub Handle_Frames()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/nested_frames"
'switch to a child frame
driver.SwitchToFrame "frame-top"
Assert.Equals 3, driver.FindElementsByTag("frame").count
'switch to child frame of "frame-top"
driver.SwitchToFrame "frame-middle"
Assert.Equals "MIDDLE", driver.FindElementById("content").Text
'switch to the default content
driver.SwitchToDefaultContent
Assert.Equals 2, driver.FindElementsByTag("frame").count
'Stop the browser
driver.Quit
End Sub

View File

@@ -0,0 +1,86 @@
Attribute VB_Name = "usage_get"
Dim Assert As New Selenium.Assert
Private Sub GetWebPage_Url()
Dim driver As New ChromeDriver
' get the main page
driver.Get "https://www.google.co.uk"
Assert.Equals "https://www.google.co.uk/", driver.URL
' get a sub page
driver.Get "/intl/en/about/"
Assert.Equals "https://www.google.co.uk/intl/en/about/", driver.URL
' get another sub page
driver.baseUrl = "https://www.google.co.uk/intl/en"
driver.Get "/policies/privacy"
Assert.Equals "https://www.google.co.uk/intl/en/policies/privacy/", driver.URL
driver.Quit
End Sub
Private Sub GetWebPage_File()
Const html As String = _
"<!DOCTYPE html>" & _
"<html lang=""en"">" & _
"<head><title>My title</title></head>" & _
"<body><h1>My content</h1></body>" & _
"</html>"
' Create the html file
Dim file$
file = Environ("TEMP") & "\mypage.html"
Open file For Output As #1
Print #1, html
Close #1
' Open it
Dim drv As New ChromeDriver
drv.Get file
Debug.Assert 0
drv.Quit
End Sub
Sub GetWebPage_DataScheme()
Const html As String = _
"data:text/html;charset=utf-8," & _
"<!DOCTYPE html>" & _
"<html lang=""en"">" & _
"<head><title>My title</title></head>" & _
"<body><h1>My content</h1></body>" & _
"</html>"
Dim drv As New ChromeDriver
drv.Get html
Debug.Assert 0
drv.Quit
End Sub
Sub GetWebPage_Javascript()
Const html As String = _
"<!DOCTYPE html>" & _
"<html lang=""en"">" & _
"<head><title>My title</title></head>" & _
"<body><h1>My content</h1></body>" & _
"</html>"
Const JS_WRITEPAGE = _
"var txt=arguments[0];" & _
"setTimeout(function(){" & _
" document.open();" & _
" document.write(txt);" & _
" document.close();" & _
"}, 0);"
Dim drv As New ChromeDriver
drv.Get "about:blank"
drv.ExecuteScript JS_WRITEPAGE, html
Debug.Assert 0
drv.Quit
End Sub

View File

@@ -0,0 +1,31 @@
Attribute VB_Name = "usage_http"
Private Assert As New Selenium.Assert
Sub Test_Native_HttpRequest()
' https://msdn.microsoft.com/en-us/library/ms535874(v=vs.85).aspx
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://vortex.data.microsoft.com/collect/v1", False
http.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36"
http.setRequestHeader "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
http.Send ""
Debug.Print http.responseText
End Sub
Sub Test_HttpRequest()
'https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest
Dim drv As New Selenium.ChromeDriver
drv.Get "https://vortex.data.microsoft.com"
Const JS_HttpRequest As String = _
"var r = new XMLHttpRequest();" & _
"r.open('GET', arguments[0], 0);" & _
"r.send();" & _
"return JSON.parse(r.responseText);"
Set result = drv.ExecuteScript(JS_HttpRequest, "https://vortex.data.microsoft.com/collect/v1")
Assert.Equals 1, result("acc")
drv.Quit
End Sub

View File

@@ -0,0 +1,102 @@
Attribute VB_Name = "usage_input"
Private Assert As New Selenium.Assert
Private Keys As New Selenium.Keys
Private Sub Handle_Input()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
'get the input box
Dim ele As WebElement
Set ele = driver.FindElementById("searchInput")
'set the text
ele.SendKeys "abc"
'get the text
Dim txt As String
txt = ele.Value
'assert text
Assert.Equals "abc", txt
driver.Quit
End Sub
Private Sub Handle_Input_With_Script()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org"
driver.FindElementById("searchInput").ExecuteScript _
"this.value=arguments[0];", "my value"
driver.Quit
End Sub
Private Sub Handle_Input_With_Autoit()
Set autoit = CreateObject("AutoItX3.Control")
autoit.Send "{ENTER}"
End Sub
Private Sub Handle_Input_With_WScript()
Set wsh = CreateObject("WScript.Shell")
wsh.SendKeys "{ENTER}"
End Sub
Private Sub Handle_TinyMCE_API()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/tinymce"
'set a content using javascript
data_set = "<p><em>12345</em></p>"
driver.ExecuteScript "tinyMCE.activeEditor.setContent(arguments[0])", data_set
'insert a content using javascript
data_instert = "<p><em>abcdefg</em></p>"
driver.ExecuteScript "tinyMCE.activeEditor.insertContent(arguments[0])", data_instert
'read and evaluate a content
data_read = driver.ExecuteScript("return tinyMCE.activeEditor.getContent()")
Assert.Equals data_instert & vbLf & data_set, data_read
driver.Quit
End Sub
Private Sub Handle_TinyMCE_Simulate()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/tinymce"
Dim btBold As WebElement, btItalic As WebElement, body As WebElement
Set btBold = driver.FindElementByCss(".mce-btn[aria-label='Bold'] button")
Set btItalic = driver.FindElementByCss(".mce-btn[aria-label='Italic'] button")
'clear body
driver.SwitchToFrame 0
Set body = driver.FindElementByTag("body")
body.Clear
'set bold and italic
driver.SwitchToDefaultContent
btBold.Click
btItalic.Click
'set and eval text
driver.SwitchToFrame 0
body.SendKeys "abcde12345"
Assert.Equals "abcde12345", body.Text
driver.Quit
End Sub

View File

@@ -0,0 +1,70 @@
Attribute VB_Name = "usage_javascript"
''
' Executes a piece of Javascript on the page.
''
Private Sub Execute_Script()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Dim title
title = driver.ExecuteScript("return document.title;")
Debug.Assert "Wikipedia, the free encyclopedia" = title
driver.Quit
End Sub
''
' Executes a piece of Javascript on a web element.
' The web element is the context itself which is "this".
''
Private Sub Execute_Script_On_Element()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Dim name
name = driver.FindElementById("searchInput") _
.ExecuteScript("return this.name;")
Debug.Assert "search" = name
driver.Quit
End Sub
''
' Executes a piece of Javascript on a collection of web elements.
' The web element is the context itself which is "this".
''
Private Sub Execute_Script_On_Elements()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Dim links
Set links = driver.FindElementsByTag("a") _
.ExecuteScript("return this.href;")
driver.Quit
End Sub
''
' Executes an asynchronous piece of Javascript.
' The script returns once "callback" is called.
''
Private Sub Execute_Script_Async()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Dim response
response = driver.ExecuteAsyncScript( _
"var r = new XMLHttpRequest();" & _
"r.onreadystatechange = function(){" & _
" if(r.readyState == XMLHttpRequest.DONE)" & _
" callback(this.responseText);" & _
"};" & _
"r.open('GET', 'wiki/Euro');" & _
"r.send();")
Debug.Print response
driver.Quit
End Sub

View File

@@ -0,0 +1,30 @@
Attribute VB_Name = "usage_list"
Private Assert As New Selenium.Assert
Private Keys As New Selenium.Keys
Private Sub Handle_Dropdown_List()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/dropdown"
Dim ele As SelectElement
Set ele = driver.FindElementById("dropdown").AsSelect
ele.SelectByText "Option 2"
Assert.Equals "Option 2", ele.SelectedOption.Text
driver.Quit
End Sub
Private Sub Handle_Multi_Select()
Dim driver As New ChromeDriver
driver.Get "http://odyniec.net/articles/multiple-select-fields"
Dim ele As WebElement
For Each ele In driver.FindElementsByXPath("//select[@name='ingredients[]']/option")
ele.Click Keys.Control
Next
driver.Quit
End Sub

View File

@@ -0,0 +1,104 @@
Attribute VB_Name = "usage_other"
Private Const JS_GET_TIMINGS As String = _
"var t=performance.timing; return [ " & _
" t.responseEnd - t.navigationStart, " & _
" t.loadEventEnd - t.responseEnd ]; "
Private Const JS_BUILD_CSS = _
"var e=this,p=[],h=function(a,s){if(!a||!s)return 0;for(var i=0,l=a.length;i<l;i" & _
"++){if(s.indexOf(a[i])==-1)return 0};return 1;};for(;e&&e.nodeType==1&&e.nodeNa" & _
"me!='HTML';e=e.parentNode){if(e.id){p.unshift('#'+e.id);break;}var i=1,u=1,t=e." & _
"localName,c=e.className&&e.className.split(/[\s,]+/g);for(var s=e.previousSibli" & _
"ng;s;s=s.previousSibling){if(s.nodeType!=10&&s.nodeName==e.nodeName){if(h(c,s.c" & _
"lassName))c=null;u=0;++i;}}for(var s=e.nextSibling;s;s=s.nextSibling){if(s.node" & _
"Name==e.nodeName){if(h(c,s.className))c=null;u=0;}}p.unshift(u?t:(t+(c?'.'+c.jo" & _
"in('.'):':nth-child('+i+')')));}return p.join(' > ');"
Private Const JS_BUILD_XPATH = _
"var e=this,p=[];for(;e&&e.nodeType==1&&e.nodeName!='HTML';e=e.parentNode){if(e." & _
"id){p.unshift('*[@id=\''+e.id+'\']');break;}var i=1,u=1,t=e.localName,c=e.class" & _
"Name;for(var s=e.previousSibling;s;s=s.previousSibling){if(s.nodeType!=10&&s.no" & _
"deName==e.nodeName){if(c==s.className)c=null;u=0;++i;}}for(var s=e.nextSibling;" & _
"s;s=s.nextSibling){if(s.nodeName==e.nodeName){if(c==s.className)c=null;u=0;}}p." & _
"unshift(u?t:(t+(c?'[@class=\''+c+'\']':'['+i+']')));}return '//'+p.join('/');"
Private Const JS_LIST_ATTRIBUTES As String = _
"var d={}, a=this.attributes; " & _
"for(var i=0; i<a.length; i++) " & _
" d[a[i].name]=a[i].value; " & _
"return d;"
Private Sub Get_Performance_Timing()
'https://developer.mozilla.org/en/docs/Web/API/Navigation_timing_API
'http://www.html5rocks.com/en/tutorials/webperformance/basics
'http://www.w3.org/TR/navigation-timing
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
times = driver.ExecuteScript(JS_GET_TIMINGS).values
Debug.Print "Timing:"
For Each T In times
Debug.Print T
Next
driver.Quit
End Sub
Private Sub Build_XPath_Locators()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Set elements = driver.FindElementsByCss("*")
Set list_xpath = elements.ExecuteScript(JS_BUILD_XPATH)
For Each txt In list_xpath
Debug.Print txt
Next
driver.Quit
End Sub
Private Sub Build_CSS_Locators()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Set elements = driver.FindElementsByCss("*")
Set list_css = elements.ExecuteScript(JS_BUILD_CSS)
For Each txt In list_css
Debug.Print txt
Next
driver.Quit
End Sub
Private Sub Build_CSS_Locators2()
Dim driver As New ChromeDriver
driver.Get "http://form.timeform.betfair.com/daypage?date=20150816"
Dim css As String
css = driver.FindElementByLinkText("Southwell") _
.ExecuteScript(JS_BUILD_CSS)
Debug.Print css
driver.Quit
End Sub
Private Sub List_Element_Attributes()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
Set element = driver.FindElementById("mw-content-text")
Set atts = element.ExecuteScript(JS_LIST_ATTRIBUTES)
For Each att In atts
Debug.Print att.key & " " & att.Value
Next
driver.Quit
End Sub

View File

@@ -0,0 +1,94 @@
Attribute VB_Name = "usage_pdf"
Private Assert As New Assert
Private Sub Handle_PDF_Chrome()
Dim driver As New ChromeDriver
driver.Get "http://static.mozilla.com/moco/en-US/pdf/mozilla_privacypolicy.pdf"
' Return the first line using the pugin API (asynchronous).
Const JS_READ_PDF_FIRST_LINE_CHROME As String = _
"addEventListener('message',function(e){" & _
" if(e.data.type=='getSelectedTextReply'){" & _
" var txt=e.data.selectedText;" & _
" callback(txt && txt.match(/^.+$/m)[0]);" & _
" }" & _
"});" & _
"plugin.postMessage({type:'initialize'},'*');" & _
"plugin.postMessage({type:'selectAll'},'*');" & _
"plugin.postMessage({type:'getSelectedText'},'*');"
' Assert the first line
Dim firstline
firstline = driver.ExecuteAsyncScript(JS_READ_PDF_FIRST_LINE_CHROME)
Assert.Equals "Websites Privacy Policy", firstline
driver.Quit
End Sub
Private Sub Handle_PDF_FF()
Const JS_WAIT_PDF_RENDERED_FIREFOX As String = _
"(function fn(){" & _
" var pdf=PDFViewerApplication.pdfViewer;" & _
" if(pdf && pdf.onePageRendered){ " & _
" pdf.onePageRendered.then(callback);" & _
" }else{" & _
" window.setTimeout(fn,60);" & _
" }" & _
"})();"
Dim driver As New ChromeDriver, Assert As New Assert
driver.Get "http://static.mozilla.com/moco/en-US/pdf/mozilla_privacypolicy.pdf"
' Wait for the first page to be rendered
driver.ExecuteAsyncScript JS_WAIT_PDF_RENDERED_FIREFOX
' Get the text from the first line
firstline = driver.FindElementByCss("#pageContainer1 > .textLayer > div:nth-child(1)").Text
' Assert the first line
Assert.Equals "Websites Privacy Policy", firstline
driver.Quit
End Sub
Private Sub Handle_PDF_FF_advanced()
' Javascript to read the PDF with the pugin API (asynchronous).
Const JS_READ_PDF_FIREFOX As String = _
"(function fn(){" & _
" var pdf=PDFViewerApplication.pdfViewer;" & _
" if(pdf && pdf.onePageRendered){ " & _
" pdf.onePageRendered.then(function(){" & _
" var pdftxt=[],cnt=pdf.pagesCount,cpt=cnt;" & _
" for(var p=1; p<=cnt; p++){" & _
" pdf.pdfDocument.getPage(p).then(function(page){" & _
" page.getTextContent().then(function(content){" & _
" var lines=[], items=content.items;" & _
" for(var i=0, len=items.length; i<len; i++)" & _
" lines.push(items[i].str);" & _
" pdftxt[page.pageIndex]=lines.join();" & _
" if(--cpt < 1) callback(pdftxt);" & _
" });" & _
" });" & _
" }" & _
" });" & _
" }else{" & _
" setTimeout(fn, 60);" & _
" }" & _
"})();"
Dim driver As New ChromeDriver
driver.Get "http://static.mozilla.com/moco/en-US/pdf/mozilla_privacypolicy.pdf"
Set pdfPages = driver.ExecuteAsyncScript(JS_READ_PDF_FIREFOX)
Debug.Print pdfPages(1) ' Print first page
driver.Quit
End Sub

View File

@@ -0,0 +1,69 @@
Attribute VB_Name = "usage_screenshot"
Private Sub Take_ScreenShot_Content()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
'take a screenshot of the page
Dim img As Image
Set img = driver.TakeScreenshot()
'save the image in the folder of the workbook
img.SaveAs ThisWorkbook.Path & "\sc-content.png"
driver.Quit
End Sub
Private Sub Take_ScreenShot_Element()
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
'take a screenshot of an element
Dim img As Image
Set img = driver.FindElementById("mp-bottom").TakeScreenshot()
'save the image in the folder of the workbook
img.SaveAs ThisWorkbook.Path & "\sc-element.png"
driver.Quit
End Sub
Private Sub Take_ScreenShot_Element_Highlight()
Const JS_ADD_YELLOW_BORDER = "window._eso=this.style.outline;this.style.outline='#FFFF00 solid 5px';"
Const JS_DEL_YELLOW_BORDER = "this.style.outline=window._eso;"
Dim drv As New ChromeDriver
drv.Get "https://en.wikipedia.org/wiki/Eurytios_Krater"
Set ele = drv.FindElementById("searchInput")
' Apply a yellow outline
ele.ExecuteScript JS_ADD_YELLOW_BORDER
' Take the screenshot
Set img = drv.TakeScreenshot()
img.SaveAs ThisWorkbook.Path & "\sc-element-highlight.png"
' Remove the outline
ele.ExecuteScript JS_DEL_YELLOW_BORDER
drv.Quit
End Sub
Private Sub Take_ScreenShot_Desktop()
Dim utils As New utils
Dim driver As New ChromeDriver
driver.Get "https://en.wikipedia.org/wiki/Main_Page"
'take a screenshot of the desktop
Set img = utils.TakeScreenshot()
'save the image in the folder of the workbook
img.SaveAs ThisWorkbook.Path & "\sc-desktop.png"
driver.Quit
End Sub

View File

@@ -0,0 +1,57 @@
Attribute VB_Name = "usage_scroll"
Private Sub Scroll_Element_To_Center()
Dim drv As New ChromeDriver
drv.Get "https://en.wikipedia.org/wiki/Main_Page"
drv.FindElementByCss("#mp-other").ExecuteScript _
"this.scrollIntoView(true);" & _
"window.scrollBy(0, -(window.innerHeight - this.clientHeight) / 2);"
Debug.Assert 0
drv.Quit
End Sub
''
' Finds all the scrollable ancestor and scroll them vertically by the provided amout of pixels
' @element {WebElement} Web element in a scrollable container or window
' @y {Long} Amount of pixels to vertically scroll
''
Private Function ScrollVertically(element As WebElement, y As Long)
Const JS_SCROLL_Y = _
"var y = arguments[0];" & _
"for (var e=this; e; e=e.parentElement) {" & _
" var yy = e.scrollHeight - e.clientHeight;" & _
" if (yy === 0) continue;" & _
" yy = y < 0 ? Math.max(y, -e.scrollTop) : Math.min(y, yy - e.scrollTop);" & _
" if(yy === 0) continue;" & _
" e.scrollTop += yy;" & _
" if ((y -= yy) == 0) return;" & _
"}" & _
"window.scrollBy(0, y);"
element.ExecuteScript JS_SCROLL_Y, y
End Function
''
' Scrolls an element in the center of the view
' @element {WebElement} Web element in a scrollable container
''
Private Function ScrollIntoViewCenter(element As WebElement)
Const JS_SCROLL_CENTER = _
"this.scrollIntoView(true);" & _
"var y = (window.innerHeight - this.offsetHeight) / 2;" & _
"if (y < 1) return;" & _
"for (var e=this; e; e=e.parentElement) {" & _
" if (e.scrollTop == 0) continue;" & _
" var yy = Math.min(e.scrollTop, y);" & _
" e.scrollTop -= yy;" & _
" if ((y -= yy) < 1) return;" & _
"}" & _
"window.scrollBy(0, -y);"
element.ExecuteScript JS_SCROLL_CENTER
End Function

View File

@@ -0,0 +1,19 @@
Attribute VB_Name = "usage_send"
Private Sub Handle_Send()
' API: https://code.google.com/p/selenium/wiki/JsonWireProtocol
Dim driver As New ChromeDriver
driver.Get "about:blank"
' Returns all windows handles
Dim hwnds As List
Set hwnds = driver.Send("GET", "/window_handles")
' Returns all links elements
Dim links As List
Set links = driver.Send("POST", "/elements", "using", "css selector", "value", "a")
Debug.Assert 0
driver.Quit
End Sub

View File

@@ -0,0 +1,47 @@
Attribute VB_Name = "usage_table"
Private Assert As New Selenium.Assert
Private Sub Scrap_Table()
Dim driver As New ChromeDriver
driver.Get "http://stats.nba.com/league/player/#!/"
driver.FindElementByCss("table.table") _
.AsTable _
.ToExcel Map:="(e) => e.firstChild.textContent.trim()"
driver.Quit
End Sub
Private Sub Handle_Table()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/tables"
'Print all cells from the second column
Dim ele As WebElement
For Each ele In driver.FindElementsByCss("#table1 tbody tr td:nth-child(2)")
Debug.Print ele.Text
Next
driver.Quit
End Sub
Private Sub Handle_Table2()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/tables"
Dim tbl As TableElement
Set tbl = driver.FindElementByCss("#table1").AsTable
'Print all cells
Dim data(): data = tbl.data
For c = 1 To UBound(data, 1)
For r = 1 To UBound(data, 1)
Debug.Print data(r, 2)
Next
Debug.Print Empty
Next
driver.Quit
End Sub

View File

@@ -0,0 +1,30 @@
Attribute VB_Name = "usage_upload"
Private Sub Upload_File_FF()
Dim file As String
file = ThisWorkbook.Path & "\mozilla_privacypolicy.pdf"
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/upload"
'Upload the file
driver.FindElementById("file-upload").SendKeys(file).Submit
'Stop the browser
driver.Quit
End Sub
Private Sub Upload_File_IE()
Dim file As String
file = ThisWorkbook.Path & "\mozilla_privacypolicy.pdf"
Dim driver As New IEDriver
driver.Get "http://the-internet.herokuapp.com/upload"
'Upload the file
driver.FindElementById("file-upload").SendKeys(file).Submit
'Stop the browser
driver.Quit
End Sub

View File

@@ -0,0 +1,33 @@
Attribute VB_Name = "usage_wait"
Private Assert As New Selenium.Assert
Private Waiter As New Selenium.Waiter
Private Sub Should_Wait_For_Delegate()
Dim driver As New ChromeDriver
' without delegate
While Waiter.Not(WaitDelegate1(), timeout:=2000): Wend
' without delegate with argument
While Waiter.Not(WaitDelegate2(driver), timeout:=2000): Wend
' with delegate on the driver
driver.Until AddressOf WaitDelegate1, timeout:=2000
' with delegate with argument
Waiter.Until AddressOf WaitDelegate1, driver, timeout:=2000
' with delegate without argument
Waiter.Until AddressOf WaitDelegate2, timeout:=2000
End Sub
Private Function WaitDelegate1()
WaitDelegate1 = True
End Function
Private Function WaitDelegate2(driver As WebDriver)
WaitDelegate2 = True
End Function

View File

@@ -0,0 +1,86 @@
Attribute VB_Name = "usage_window"
Private Assert As New Selenium.Assert
Private Sub Windows_Switch()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/windows"
driver.FindElementByCss(".example a").Click
'Switch to a new window
driver.SwitchToNextWindow
Assert.Equals "New Window", driver.title
'Switch to the previous activated window
driver.SwitchToPreviousWindow
Assert.NotEquals "New Window", driver.title
'Stop the browser
driver.Quit
End Sub
Private Sub Window_Maximize()
Dim driver As New ChromeDriver
driver.Get "about:blank"
driver.Window.Maximize
Debug.Assert 0
driver.Quit
End Sub
Private Sub Window_SetSize()
Dim driver As New ChromeDriver
driver.Get "about:blank"
driver.Window.SetSize 800, 600
Debug.Assert 0
driver.Quit
End Sub
Private Sub Windows_Close()
Dim driver As New ChromeDriver
driver.Get "http://the-internet.herokuapp.com/windows"
' Save the main window
Set winMain = driver.Window
' Open a new window
driver.FindElementByCss(".example a").Click
' Close all the newly opened windows
For Each win In driver.Windows
If Not win.Equals(winMain) Then win.Close
Next
winMain.Activate
'Stop the browser
driver.Quit
End Sub
Private Sub Windows_Open_New_Tab()
Dim driver As New ChromeDriver, Keys As New Keys
driver.Get "http://the-internet.herokuapp.com/windows"
' Holds the control key while clicking
driver.FindElementByLinkText("Dropdown").Click Keys.Control
driver.SwitchToNextWindow
'Stop the browser
driver.Quit
End Sub
Private Sub Windows_Open_New_One2()
Dim driver As New ChromeDriver, Keys As New Keys
driver.Get "about:blank"
driver.ExecuteScript "window.open(arguments[0])", "http://www.google.com/"
driver.SwitchToNextWindow
'Stop the browser
driver.Quit
End Sub

View File

@@ -0,0 +1,90 @@
Attribute VB_Name = "utils"
Private Declare PtrSafe Function FindWindowExA Lib "user32.dll" ( _
ByVal hwndParent As LongPtr, _
ByVal hwndChildAfter As LongPtr, _
ByVal lpszClass As String, _
ByVal lpszWindow As String) As Long
Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc.dll" ( _
ByVal hwnd As LongPtr, _
ByVal dwId As Long, _
ByRef riid As Any, _
ByRef ppvObject As IAccessible) As Long
''
' Loads a translation table in a dictionary from a worksheet
' The first column is the result and second is the input
' Usage:
' Set dict = LoadTranslation([Sheet5])
' Debug.Print = dict("Cancel")
''
Public Function LoadTranslation(sheet As Worksheet) As Collection
Dim values(), translation$
Set LoadTranslation = New Collection
values = sheet.Cells.CurrentRegion.Value2
For r = LBound(values) To UBound(values)
If Not IsEmpty(values(r, 1)) Then translation = values(r, 1)
LoadTranslation.Add translation, values(r, 2)
Next
End Function
''
' Returns all the active instances of Excel
''
Public Function GetExcelInstances() As Collection
Dim guid&(0 To 4), app As Object, hwnd
guid(0) = &H20400
guid(1) = &H0
guid(2) = &HC0
guid(3) = &H46000000
Set GetExcelInstances = New Collection
Do
hwnd = FindWindowExA(0, hwnd, "XLMAIN", vbNullString)
If hwnd = 0 Then Exit Do
hwnd = FindWindowExA(hwnd, 0, "XLDESK", vbNullString)
If hwnd Then
hwnd = FindWindowExA(hwnd, 0, "EXCEL7", vbNullString)
If hwnd Then
If AccessibleObjectFromWindow(hwnd, &HFFFFFFF0, guid(0), app) = 0 Then
GetExcelInstances.Add app.Application
End If
End If
End If
Loop
End Function
''
' Returns True if a file is locked by another application, False otherwise
''
Public Function IsFileLocked(file_path As String) As Boolean
Dim num As Long
On Error Resume Next
Name file_path As file_path
num = Err.Number
On Error GoTo 0
If num <> 0 And num <> 75 Then Error num
IsFileLocked = num <> 0
End Function
''
' A simple hash function
''
Public Function HashFnv$(str As String)
Dim bytes() As Byte, i&, lo&, hi&
lo = &H9DC5&
hi = &H11C&
bytes = str
For i = 0 To UBound(bytes) Step 2
lo = 31& * ((bytes(i) + bytes(i + 1) * 256&) Xor (lo And 65535))
hi = 31& * hi + lo \ 65536 And 65535
Next
lo = (lo And 65535) + (hi And 32767) * 65536 Or (&H80000000 And -(hi And 32768))
HashFnv = Hex(lo)
End Function

View File

@@ -0,0 +1,5 @@
@REM start excel by yourself
@REM ./test.xlsm
xlwings vba edit --file ./test.xlsm

View File

@@ -0,0 +1,5 @@
@REM start excel by yourself
@REM ./test.xlsm
xlwings vba edit --file ./test.xlsm

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
helloworld
</body>
</html>

View File

@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>navigator.Webdriver test</title>
</head>
<body>
<h1>navigator.Webdriver test</h1>
<p id="msg">show user agent, should show undefined</p>
<script>
let element = document.getElementById("msg");
element.insertAdjacentHTML("afterend", '<p id="webdriver-result">' + navigator.Webdriver + "</p>");
</script>
</body>
</html>

View File

@@ -0,0 +1,5 @@
Option Explicit
Sub helloworld()
Worksheets ("Sheet1")
End Sub

View File

@@ -0,0 +1,3 @@
@REM rmdir *.bas
xlwings vba edit --file .\main.xlsm

View File

@@ -0,0 +1,4 @@
git pull
git add .
git commit -m"update armandarmand task1-tciket1,"
start git push

View File

@@ -0,0 +1,8 @@
Attribute VB_Name = "CheckLastRow"
Option Explicit
Function run(row as integer)
Dim last_check_row as integer
Dim last_row as boolean
End Function

View File

@@ -0,0 +1,97 @@
Option Explicit
Global TARGET_SHEET as string
Global ROW_START as Integer
Global ChromiumBinaryPath As String
Global COL_STOCK_CODE As String
Global COL_STOCK_NAME As String
Global COL_STOCK_PRICE As String
Global COL_10_DAY_MOVING_AVERAGE As String
Global COL_20_DAY_MOVING_AVERAGE As String
Global COL_50_DAY_MOVING_AVERAGE As String
Global COL_100_DAY_MOVING_AVERAGE As String
Global COL_250_DAY_MOVING_AVERAGE As String
Global COL_P_E_RATIO_EXPECTED As String
Global COL_EARNINGS_PER_SHARE As String
Global COL_YIELD As String
Global COL_FUND_FLOW As String
Global COL_SHORT_SELLING_AMOUNT_RATIO_ As String
Global COL_RSI_10 As String
Global COL_RSI_14 As String
Global COL_RSI_20 As String
Global COL_MACD_8_17_DAYS As String
Global COL_MACD_12_25_DAYS As String
Global IDX_STOCK_CODE As Integer
Global IDX_STOCK_NAME As Integer
Global IDX_STOCK_PRICE As Integer
Global IDX_10_DAY_MOVING_AVERAGE As Integer
Global IDX_20_DAY_MOVING_AVERAGE As Integer
Global IDX_50_DAY_MOVING_AVERAGE As Integer
Global IDX_100_DAY_MOVING_AVERAGE As Integer
Global IDX_250_DAY_MOVING_AVERAGE As Integer
Global IDX_P_E_RATIO_EXPECTED As Integer
Global IDX_EARNINGS_PER_SHARE As Integer
Global IDX_YIELD As Integer
Global IDX_FUND_FLOW As Integer
Global IDX_SHORT_SELLING_AMOUNT_RATIO_ As Integer
Global IDX_RSI_10 As Integer
Global IDX_RSI_14 As Integer
Global IDX_RSI_20 As Integer
Global IDX_MACD_8_17_DAYS As Integer
Global IDX_MACD_12_25_DAYS As Integer
Global COL_RESULT As String
Sub init()
ChromiumBinaryPath = "C:\Users\logic\AppData\Local\Chromium\Application\chrome.exe"
TARGET_SHEET = "Sheet1"
ROW_START = 11
COL_STOCK_CODE = "A"
COL_STOCK_NAME = "B"
COL_STOCK_PRICE = "C"
COL_10_DAY_MOVING_AVERAGE = "D"
COL_20_DAY_MOVING_AVERAGE = "E"
COL_50_DAY_MOVING_AVERAGE = "F"
COL_100_DAY_MOVING_AVERAGE = "G"
COL_250_DAY_MOVING_AVERAGE = "H"
COL_P_E_RATIO_EXPECTED = "L"
COL_EARNINGS_PER_SHARE = "M"
COL_YIELD = "N"
COL_FUND_FLOW = "O"
COL_SHORT_SELLING_AMOUNT_RATIO_ = "P"
COL_RSI_10 = "Q"
COL_RSI_14 = "R"
COL_RSI_20 = "S"
COL_MACD_8_17_DAYS = "V"
COL_MACD_12_25_DAYS = "W"
COL_RESULT = "AE"
IDX_STOCK_CODE = 0
IDX_STOCK_PRICE = 1
IDX_STOCK_NAME = 2
IDX_10_DAY_MOVING_AVERAGE = 4
IDX_20_DAY_MOVING_AVERAGE = 5
IDX_50_DAY_MOVING_AVERAGE = 6
IDX_100_DAY_MOVING_AVERAGE = 7
IDX_250_DAY_MOVING_AVERAGE = 8
IDX_P_E_RATIO_EXPECTED = 9
IDX_EARNINGS_PER_SHARE = 10
IDX_YIELD = 11
IDX_FUND_FLOW = 12
IDX_SHORT_SELLING_AMOUNT_RATIO_ = 13
IDX_RSI_10 = 14
IDX_RSI_14 = 15
IDX_RSI_20 = 16
IDX_MACD_8_17_DAYS = 17
IDX_MACD_12_25_DAYS = 18
End Sub

View File

@@ -0,0 +1,96 @@
Attribute VB_Name = "FetchAaStock"
Dim driver As New ChromeDriver
Function run(stock_num as integer)
' On Error GoTo eh
Dim fetch_result(0 To 22) As String
driver.SetBinary ChromiumBinaryPath
driver.AddArgument "--disable-blink-features=AutomationControlled"
driver.Start
' ' driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
' ' driver.ExecuteScript "alert('helloworld')"
driver.ExecuteScript "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
' ' driver.Get "http://localhost:8080/navigator_webdriver_test.html"
' ' https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html
' driver.Get "https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html"
' driver.ExecuteScript "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
driver.Get "http://www.aastocks.com"
' driver.ExecuteScript "console.log('hello excel')"
driver.ExecuteScript "document.querySelector('#sb-txtSymbol-aa').value = '"& stock_num &"'"
driver.ExecuteScript "document.querySelector('#sb-btnSubmit').click()"
driver.ExecuteScript "document.querySelectorAll('span.float_l')[6].click()"
Debug.Print driver.ExecuteScript("{ return 'helloworld from chrome' }")
' stock_Name # Name
fetch_result(IDX_STOCK_NAME)= driver.ExecuteScript("{ return document.querySelector('#SQ_Name').textContent.trim() }")
' stock_Price # Price
fetch_result(IDX_STOCK_PRICE)= driver.ExecuteScript("{ return document.querySelector('#labelLast').textContent.trim() }")
' 10_day_Moving_Average # 10????
fetch_result(IDX_10_DAY_MOVING_AVERAGE)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel.dq-panel')[1].querySelectorAll('tr')[1].querySelectorAll('td')[1].textContent.trim() }")
' 20_day_Moving_Average # 20????
fetch_result(IDX_20_DAY_MOVING_AVERAGE)= "20_day_Moving_Average missing"
' 50_day_Moving_Average # 50????
fetch_result(IDX_50_DAY_MOVING_AVERAGE)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel.dq-panel')[1].querySelectorAll('tr')[2].querySelectorAll('td')[1].textContent.trim() }")
' 100_day_Moving_Average # 100????
fetch_result(IDX_100_DAY_MOVING_AVERAGE)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel.dq-panel')[1].querySelectorAll('tr')[3].querySelectorAll('td')[1].textContent.trim() }")
' 250_day_Moving_Average # 250????
fetch_result(IDX_250_DAY_MOVING_AVERAGE)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel.dq-panel')[1].querySelectorAll('tr')[4].querySelectorAll('td')[1].textContent.trim() }")
' P_E_Ratio_Expected # ???/??
fetch_result(IDX_P_E_RATIO_EXPECTED)= driver.ExecuteScript("{ return document.querySelectorAll('#tbPERatio div')[5].textContent.trim() }")
' Earnings_per_Share # ??????
fetch_result(IDX_EARNINGS_PER_SHARE)= "earnings_per_share is missing"
' Yield # ???
fetch_result(IDX_YIELD)= driver.ExecuteScript("{ return document.querySelectorAll('.quote-box div')[19].textContent.trim() }")
' Fund_Flow # ????
fetch_result(IDX_FUND_FLOW)= driver.ExecuteScript("{ return document.querySelectorAll('.quote-box div')[29].textContent.trim() }")
' Short_Selling_Amount_Ratio_% # ???_??(%)
fetch_result(IDX_SHORT_SELLING_AMOUNT_RATIO_)= driver.ExecuteScript("{ return document.querySelectorAll('.quote-box div')[4].textContent.trim() }")
' RSI_10 # RSI 10
fetch_result(IDX_RSI_10)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel')[7].querySelectorAll('table')[0].querySelectorAll('tr')[0].querySelector('.txt_r').textContent.trim() }")
' RSI_14 # RSI 14
fetch_result(IDX_RSI_14)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel')[7].querySelectorAll('table')[0].querySelectorAll('tr')[0].querySelector('.txt_r').textContent.trim() }")
' RSI_20 # RSI 20
fetch_result(IDX_RSI_20)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel')[7].querySelectorAll('table')[0].querySelectorAll('tr')[1].querySelector('.txt_r').textContent.trim() }")
' MACD_8_17_days # MACD(8_17 ?)
fetch_result(IDX_MACD_8_17_DAYS)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel')[7].querySelectorAll('table')[0].querySelectorAll('tr')[2].querySelector('.txt_r').textContent.trim() }")
' MACD_12_25_days # MACD(12/25 ?)
fetch_result(IDX_MACD_12_25_DAYS)= driver.ExecuteScript("{ return document.querySelectorAll('.content.comm-panel')[7].querySelectorAll('table')[0].querySelectorAll('tr')[3].querySelector('.txt_r').textContent.trim() }")
' Application.Wait Now + TimeValue("00:30:01")
driver.Quit
Done:
' Debug.Print "hello done"
run = fetch_result
Exit Function
eh:
Debug.Print "hello error"
End Function

View File

@@ -0,0 +1,5 @@
Attribute VB_Name = "GetLastCheckRow"
Function run(first_row As Integer)
getLastCheckRow = first_row + 10
End Function

View File

@@ -0,0 +1,74 @@
Option Explicit
Dim rowc, cc, columnC As Integer
Sub helloworld()
' On Error GoTo eh
Config.init
Dim temp as Variant
' Debug.print ReadStockCode.run(11)
temp = FetchAaStock.run(268)
' Debug.print temp(IDX_STOCK_PRICE)
Debug.print temp(IDX_STOCK_NAME)
Write_10DayMovingAverage.run 11, CStr(temp(IDX_10_DAY_MOVING_AVERAGE))
Write_50DayMovingAverage.run 11, CStr(temp(IDX_50_DAY_MOVING_AVERAGE))
Write_100DayMovingAverage.run 11, CStr(temp(IDX_100_DAY_MOVING_AVERAGE))
Write_250DayMovingAverage.run 11, CStr(temp(IDX_250_DAY_MOVING_AVERAGE))
WriteRsi_10.run 11, CStr(temp(IDX_10_DAY_MOVING_AVERAGE))
WriteRsi_14.run 11, CStr(temp(IDX_50_DAY_MOVING_AVERAGE))
WriteRsi_20.run 11, CStr(temp(IDX_50_DAY_MOVING_AVERAGE))
WriteMACD_8_17Days.run 11, CStr(temp(IDX_MACD_8_17_DAYS))
WriteMACD_12_25Days.run 11, CStr(temp(IDX_MACD_12_25_DAYS))
WriteEarningsPerShare.run 11, CStr(temp(IDX_EARNINGS_PER_SHARE))
WriteFundFlow.run 11, CStr(temp(IDX_FUND_FLOW))
WritePERatioExpected.run 11, CStr(temp(IDX_P_E_RATIO_EXPECTED))
WriteShortSellingAmountRatio.run 11, CStr(temp(IDX_SHORT_SELLING_AMOUNT_RATIO_))
' WriteStockCode.run 11, CStr(temp(IDX_STOCK_CODE))
WriteStockName.run 11, CStr(temp(IDX_STOCK_NAME))
WriteStockPrice.run 11, CStr(temp(IDX_STOCK_PRICE))
WriteYield.run 11, CStr(temp(IDX_YIELD))
' driver.SetBinary ChromiumBinaryPath
' driver.Start
' driver.AddArgument "--disable-blink-features=AutomationControlled"
' ' driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
' ' driver.ExecuteScript "alert('helloworld')"
' ' driver.ExecuteScript "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
' ' driver.Get "http://localhost:8080/navigator_webdriver_test.html"
' ' https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html
' ' driver.Get "https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html"
' driver.ExecuteScript "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
' driver.Get "http://www.aastocks.com"
' driver.ExecuteScript "console.log('hello excel')"
' driver.ExecuteScript "document.querySelector('#sb-txtSymbol-aa').value = '939'"
' driver.ExecuteScript "document.querySelector('#sb-btnSubmit').click()"
' Debug.Print driver.ExecuteScript("return 'helloworld'")
Application.Wait Now + TimeValue("00:00:01")
Done:
Debug.Print "hello done"
Exit Sub
eh:
Debug.Print "hello error"
End Sub

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadEarningsPerShare"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadFundFlow"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadMACD_12_25Days"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadMacd_8_17Days"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadPERatioExpected"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadRsi_10"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadRsi_14"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadRsi_20"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadShortSellingAmountRatio"

View File

@@ -0,0 +1,7 @@
Attribute VB_Name = "ReadStockCode"
Option Explicit
Function run(row as integer)
run = Worksheets("Sheet1").Range("A" & CStr(row)).Value
End Function

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadStockName"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadStockPrice"

View File

@@ -0,0 +1 @@
Attribute VB_Name = "ReadYield"

Some files were not shown because too many files have changed in this diff Show More