VBA Chrome Dev Tool screenshot - vba

I am working on an automation project. I want to do full page (scroll down) screenshot. While the Chrome default Developer Tool (Ctr+Shift+i, Ctr+Shift+p, >capture full size screenshot) does a great job. However, is it possible to pass this instruction in VBA? I am using https://github.com/longvh211/Chromium-Automation-with-CDP-for-VBA
I have tried using VBA's sendkey methods but result is not ideal as the page is long (scroll down to one more screen). Should I use the Page.captureScreenshot() method? i.e. save the output to a string, and save the string as a PNG file.
Unable to get the output as img_string is empty:
Dim objBrowser As New clsBrowser
Dim img_string As String
Dim bytes() As Byte
objBrowser.start "edge", cleanActiveSession:=True
'By default, the new window is minimized, use .show to bring it out
objBrowser.show
'Navigate and wait 'The wait method, if till argument is omitted, will by default wait until ReadyState = complete
objBrowser.navigate "https://www.livingwaters.com/movie/the-atheist-delusion/"
objBrowser.wait till:="interactive" 'only need to wait until page is interactable. Refer to definition for other options
img_string = objBrowser.jsEval("await page.captureScreenshot()")

Related

Data extraction using Selenium in MS access vba

I am currently using below mentioned code in MS Access vba and code is extracting main class data but not extraction sub classes data as object required error is visible during execution.My code is given below.
Const URL As String = "https://www.tmdn.org/tmview/#/tmview/results?page=1&pageSize=30&criteria=C&basicSearch=BolĂ­grafo"
Dim myproduct As Selenium.WebElement
Set d = New ChromeDriver
With d
.Start "Chrome"
.Get URL
Sleep 40000
Dim element As Selenium.WebElement
Dim elements As Selenium.WebElements
Set elements = .FindElementsByCss("div[class=rt-tr-group]")
For Each element In elements
trade = element.FindElement(By.className("sc-pZopv gQWHwO")).Text
Next element
MsgBox (trade)
Your "Sleep 40000" line may not be adequate.
since internet response times can vary widely - such an absolute time mechanism is not a reliable means of assuring that the web content is "fully loaded/retrieved".
You need to look into other means of assuring that the web page is "fully loaded".

How do I open a user's default browser open to the users homepage?

I am trying to figure out how to cause a Menu Strip item to open the active Windows accounts default browser to their homepage. I have tried Process.Start("about:blank") and for some reason this always opens Internet Explorer's about:blank page. (I have Google Chrome as my default browser with http://www.duckduckgo.com as its homepage on Windows 7 Pro.)
I know I can specify any URL to open the default browser, but how to get their selected homepage to open? I have found some articles based in C# that required looking into registry entries as to finding their chosen homepage per each browser. Would the process be the same/similar in VB.Net 2017 and how would I go about doing so? This is using VB.Net 2017 Community Edition and the project is a Windows.Forms desktop application.
The only way I found is to manually query the registry about the default command to handle the http protocol.
The first line of this code will return something like "C:\Program Files\Your Browser\browser.exe" -osint -url "%1", so you want to replace %1 by your landing page.
Then, if you want to use Process.Start with command line arguments, the first parameter will be the command and the second one the arguments.
Thus, we need to split the registry string between the command and the argument list. The regex will do this job.
I omited null checks and regex success for clarity.
Dim cmd = CStr(Registry.ClassesRoot.OpenSubKey("http\shell\open\command").GetValue(String.Empty))
cmd = cmd.Replace("%1","about:blank")
Dim r = new Regex("^""([^""]+)"" (.*)")
Dim m = r.Match(cmd)
Process.Start(m.Groups(1).Value, m.Groups(2).Value)
Found some clues here.
Dim readValue As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\
Associations\UrlAssociations\http\UserChoice", "Progid", Nothing).ToString
Will give an identifier for the current user's browser.
Dim path As String = My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\"
& readValue & "\shell\open\command", "", Nothing).ToString
Will return the run command with path.
Add some code to extract the EXE and run it without arguments, for example;
Dim DivArr As Char() = {Chr(34), "\"c}
'split into segments using quotes and back-slash seperators
Dim parts() As String = path.Split(DivArr)
'find first segment with period/full-stop
Dim Executable As String = Array.Find(parts, Function(x) (x.Contains(".")))
Process.start(Executable)
You may try this:
Process.Start("your_url_here eg. www.homepage.com etc.")
and, this will open with google chrome if its your default browser.

How Do I Autoatically Copy Website Address URL

I'm a journalist. I spend countless hours copying brief passages from various webpages, and then pasting those passages - along with attribution to the websites I found them - into web-based articles.
For example, many of my articles have passages which look like this:
The Mexican finance minister wrote:
The euro exchange rate is, strictly speaking, too low for the German economy's competitive position.
I want to use VBA to do the following:
(1) When I highlight the text I want to copy - in the example "The euro exchange rate is, strictly speaking, too low for the German economy's competitive position"
(2) I would also automatically copy the url where the text comes from (in this case, http://www.cnbc.com/2017/02/06/german-finance-minister-agrees-euro-too-low-for-germany.html)
(3) So when I paste the text into my blog, it would automatically paste the text and ALSO the url. In other words, I would end up with what I wrote above.
I think the write script is IE.LocationURL to automatically determine the url I'm at. And I know how to launch Internet Explorer and navigate to a web page.
But I don't know how to put the script together.
Here's my attempt:
Const READYSTATE_COMPLETE = 4
' Declare Windows API function for setting active window
Declare Function SetForegroundWindow Lib "user32" _
Alias "SetForegroundWindow" (ByVal Hwnd As Long)As Long
' Declare Internet Explorer object
Dim IE As SHDocVw.InternetExplorer
Sub Main
' create instance of InternetExplorer
Set IE = New InternetExplorer
' using your newly created instance of Internet Explorer
With IE
SetForegroundWindow IE.HWND
.Visible = True
.Navigate2 "http://www.cnbc.com/2017/02/06/german-finance-minister-agrees-euro-too-low-for-germany.html"
' Wait until page we are navigating to is loaded
Do While .Busy
Loop
Do
Loop Until .ReadyState = READYSTATE_COMPLETE
On Error Resume Next
If Err Then
'Do Nothing
Else
'Copy the selected text
SendKeys "^c"
' Here's where I'm trying to copy the url
debug.print.IE.LocationURL
End With
End If
' Tidy Up
Set IE = Nothing
End Sub
I would then run another script to automatically log into my publishing platform and paste the copied text and url info. Ideally, it would be pasted in the format shown at the top of this post (with linked text and then indented quote).
But if I just have the copied text and url, that would still save me a lot of time.
I use Nuance Dragon Naturally Speaking to run my VBA scripts.
But I'm lost. Please help steer me in the right direction! Thanks!
UPDATE: I guess what I really need is a way to store the url as a string. I can then later write the string (and just paste the selected text the old-fashioned way, with control-v.)
So does anyone know how to read and store the url as a string or value?
Playing around with a bunch of possibilities, I think I finally created a script which works.
To do it, I
(1) first have to copy the url manually from the web page by highlighting the url and the copying it to clipboard using control-c on my keyboard;
(2) select (i.e. manually highlight with my keyboard) the text within the article which I want to copy.
Here's the script:
Sub Main
Dim MyData As DataObject
Dim strClip As String
Set MyData = New DataObject
MyData.GetFromClipboard
strClip = MyData.GetText
Wait 5
SendKeys "^c"
'I have code here to open up the webpage where I'm inserting the information
SendKeys "^v"
' The line above pastes the text I have selected
SendKeys strClip
' The line above sends the url which I previously saved
End Sub
I don't know if it's the most efficient or elegant solution, but it works.

Use Selenium Driver to load page, dismiss/dispose it and keep browser active

I am using Selenium Webdriver to load a specific feature from an application, a rich text editor (actually a custom release of CKEditor) and the code below works perfectly for that... except that I would like to release Selenium objects (and geckodriver.exe/marionnette black cmd window) since the desired page was loaded. But either .Close(), .Quit() or .Dispose() methods will wipe out the Firefox window as well...
Is there a way to dismiss Selenium Webdriver and keep Firefox running by its own?
Thank you very much
Private Sub LoadResource()
Dim FFD As New OpenQA.Selenium.Firefox.FirefoxDriver()
'Set timeout of 60 seconds for steps to complete successfully
Dim WDW As New OpenQA.Selenium.Support.UI.WebDriverWait(FFD, TimeSpan.FromSeconds(60))
'navigate to login page
FFD.Navigate.GoToUrl("https://www.myapplication.com/login")
'Wait until application loads main page (this means login was successful)
WDW.Until(Function() FFD.Url = "https://www.myapplication.com/")
'Load built-in rich text editor Rich text
FFD.Navigate.GoToUrl("https://www.myapplication.com/editor?document=1080199")
'Wait for successful loading of the editor page
WDW.Until(Function() FFD.Url = "https://www.myapplication.com/editor?document=1080199")
'That's all.
'here I'd like to release Firefox to keep running and get rid of WebDriver's objects and resources, if possible.
End Sub
This is based on Kirhgoph's comment and seems to work well:
Private Sub LoadResource()
Dim FFD As New OpenQA.Selenium.Firefox.FirefoxDriver()
Dim GDP As Process = Process.GetProcessesByName("geckodriver").Last
Dim WDW As New OpenQA.Selenium.Support.UI.WebDriverWait(FFD, TimeSpan.FromSeconds(60))
FFD.Navigate.GoToUrl("https://www.myapplication.com/login")
WDW.Until(Function() FFD.Url = "https://www.myapplication.com/")
FFD.Navigate.GoToUrl("https://my.application.com/editor?document=1080199")
WDW.Until(Function() FFD.Url = "https://www.myapplication.com/editor?document=1080199")
GDP.CloseMainWindow()
GDP.WaitForExit()
FFD.Quit()
End Sub

Getting selected files filepath without OpenFileDialog

I was wondering if there is anyway to get the file path of a selected file. I have registered a hotkey in reference to this.
E.g. RegisterHotKey(Me.Handle, 100, MOD_CONTROL Or MOD_SHIFT, Keys.D2)
Which will do certain actions on pressing ctrl, shift and 2. What i want to do is to get the path of a selected file WITHOUT opening OpenFileDialog
e.g. i select mydoc.doc located on my desktop, press ctrl shift and 2, and it will msgbox out the location of the file.
(meaning i click the file mydoc.doc on my desktop, press my hotkey and get the file location. Is there anyway to do this? (Just like how you would click a file in a folder to copy and paste it to another location, i want to click the file press my hotkey and msgbox out its location))
Is there anyway to do this or any direction anyone can point me in?Because i can't find any API which does this...
Thanks!
EDIT:
After reading all the updates and the several links here and there, I started to construct my own function for this, I'm just at the part to determine how many selected icons there are, but i keep getting back 0 icons is there something wrong with what I'm doing?
Public Function getDesktopFiles() As String
Dim vhandle As IntPtr = FindWindow("Progman", "Program Manager")
vhandle = FindWindowEx(vhandle, IntPtr.Zero, "SHELLDLL_DefView", vbNull)
vhandle = FindWindowEx(vhandle, IntPtr.Zero, "SysListView32", "FolderView")
Dim vItemcount As IntPtr
vItemcount = SendMessage(vhandle, LVM_GETSELECTEDCOUNT, 0, 0)
Return vItemcount
End Function
This question has a link to a Raymond Chen blog post which will give you the API calls you require, you will need to convert it to VB but it is based on COM so should be easy. The other answer to that question gives the C# version of Raymond's code...
Edited to add specifics:
1. Include project references to Microsoft Internet Controls (to get the SHDocVw namespace) and Microsoft Shell Controls and Automation (to get the Shell32 namespace)
2. Use SHDocVw.ShellWindows to get an enumeration of open browser windows.
3. Try to cast each item as a ShellBrowserWindow, and then try to cast the Document property as a Shell32.IShellFolderViewDual2 object.
4. The FocusedItem property gives the selected item.
VB.NET code:
Dim windows As New SHDocVw.ShellWindows
For Each window As Object In windows
Dim browser As SHDocVw.ShellBrowserWindow = window
Dim folder As Shell32.IShellFolderViewDual2 = browser.Document
Console.WriteLine(folder.FocusedItem.Path)
Next