Unable to click selenium chromedriver - vb.net

I'm unable to perform click by cssselector or even xpath or even send keys space or enter.
I think youtube is blocking it. Any help appreciate.
My Code:
Public Function OpenVideo(video As String)
Try
Form1.UpdateStatus("Opening video ...")
If (Driver Is Nothing) Then
Return ""
End If
_Status = True
Driver.Navigate().GoToUrl(video)
'Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5)
'TESTING
' Driver.SwitchTo.Frame(0)
Dim element = Driver.FindElementByCssSelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > span:nth-child(2) > button[aria-label='Play (k)'")
element.click()
ViewsByVideo = 0
d = DateTime.Now
If (clockTimer Is Nothing) Then
Dim autoEvent As New AutoResetEvent(False)
clockTimer = New Timer(AddressOf ClockFunction, autoEvent, 0, 1000)
Else
clockTimer.Change(0, 1000)
End If
IsPlaying = True
Catch ex As Exception
LogManager.AddLog(ex.Message)
End Try
_Status = False
End Function
If possible I would like to instead of clicking elements or button, just "HIT SPACE" and this way I can be sure it always press play as space is the same like play.
Thanks

google blocks automated traffic
try using cssSelector at final step.
if that didn't work then might be there is DOM issue with page or automated script is blocked.

Related

How to check the visibility of the element in Edge Browser using VBA Selenium and alternative to Obj.Wait

Unable to check the visibility of the element. Please guide
At present using Obj.Wait to wait so that Site is loaded fully. Is there any other way which can check the Edge Browser has loaded fully before execution of next code
In the instant case
Obj.Wait 580000
If Obj.IsElementPresent(By.XPath("//*[#id='downloadReport']/div")) = True Then
I have a following VBA code + Selenium which is opening a website, populate data from Excel and displays the record.
Dim Obj As New WebDriver
Sub EdgeAutoSF1CRA0()
Set Obj = New Selenium.EdgeDriver
Dim By As New Selenium.By
Obj.SetCapability "ms:edgeOptions", "{""excludeSwitches"":[""enable-automation""]}"
Obj.Start "edge", ""
Obj.Get "https://************
Obj.Window.Maximize
Obj.FindElementByName("croreAccount").SendKeys ("Search")
Obj.FindElementByXPath("//*[#id='loadSuitFiledDataSearchAction']/div[1]/div[3]/div[4]/img").Click
Obj.FindElementById("borrowerName").SendKeys (ThisWorkbook.Sheets("Sheet1").Range("C5").Value)
Obj.FindElementByXPath("//*[#id='search-button']/ul/li[1]/div/input").Click
Obj.Wait 580000
If Obj.IsElementPresent(By.XPath("//*[#id='downloadReport']/div")) = True Then
Obj.FindElementByXPath("//*[#id='downloadReport']/div").Click
Else
Obj.FindElementByXPath("//*[#id='three-icons']/ul/li[3]/a/div").Click
End If
'Call EdgeAutoSF25LA0
End Sub
If match is found, then element
XPath("//*[#id='downloadReport']/div")
is visible. The code at site is
'a href="downloadStatusReport" id="downloadReport">Download</a
If no match is found, then element
XPath("//*[#id='downloadReport']/div")
is not visible. The code at site is
'a href="downloadStatusReport" id="downloadReport" style="display: none;">Download</a

Is there a way to retrieve text from a webpage to a TextBox in VB.NET?

Let say I have a TextBox1 and a SaveButton. A website "www.example.com/code1.text" with just a content:
303981
How to retrieve this 303981 to a TextBox?
Do we need a WebBrowser1?
Please help me I'm self learning and beginner also.
Look at the System.Net.WebClient type.
Using wc As New WebClient()
TextBox1.Text = wc.DownloadString("www.example.com/code1.text")
End Using
You need to place a webbrowser control on your form. I would use CefSharp for this
(see: https://www.youtube.com/watch?v=6d-AgfFzr70)
then you can do something like:
settings = New CefSettings
CefSharp.Cef.Initialize(settings)
browser = New ChromiumWebBrowser("www.google.com")
Which loads google.com, just change it to the page you want to load.
Now check your website and see if you can get that textbox value by javascript from the console (F12). Check the source if you can access it with it's ID or that you need to use it's class.
for example:
document.getElementsByClassName('textboxclass')[0].value;
if you manage to get the right value back in your browser console, you can go ahead in your program and do somethinh like:
Dim task As Task(Of JavascriptResponse) = browser.EvaluateScriptAsync(code)
where code contains your javascript.
you may do something like:
task.ContinueWith(
Sub(t)
Try
If t.IsFaulted = False And t.Result IsNot Nothing Then
Dim response = t.Result 'Error: Result is not a member of Task'
If response.Success And response.Result IsNot Nothing Then
taskResult = response.Result
Else
taskResult = "bad result"
End If
End If
Catch ex As Exception
'Dbg("!!!!!!!!!!!!!!! Exception: " & ex.ToString)
taskResult = ex.ToString
End Try
End Sub)
to get the result in a string.

Is there a better way to accomplish this loop?

I'm pretty new with VBA, but I've been muddling through to make a program for my team.
This piece of code works most of the time, but tends to hang on occasion. I can't figure out why it would hang sometimes, and work perfectly most of the time, so I'm now trying to figure out a better way to accomplish this loop. I know that this method of looping isn't the best way to do things, but not sure how to accomplish the task.
My webpage operates in a PEGA Web application, and the native IE ready state indicators are always 'ready' so I have to use the web application's ready state markers.
Can anyone help me out?
Public Sub WaitingForRS()
' FIND THE C360 WINDOW
Marker = 0
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
On Error Resume Next
my_url = objShell.Windows(x).Document.Location
my_title = objShell.Windows(x).Document.title
If my_title Like "Coverage User" & "*" Then
Set C360Window = objShell.Windows(x)
Marker = 1
Exit For
Else
End If
Next
If Marker = 0 Then
MsgBox ("C360 window is not found. Please ensure C360 is open in Internet Explorer and try again")
Else
End If
'FIND THE READY STATE INDICATOR
RSIndicatorDocMarker = 0
RSIndicatorDataMarker = 0
Set RSIndicatorPage = C360Window.Document
Set RSIndicatorClass = RSIndicatorPage.getelementsbyclassname("document-statetracker")(0)
RSIndicatorCheck:
'CHECK THE READY STATE DOC STATUS
If RSIndicatorClass.getattribute("data-state-doc-status") = "ready" Then
RSIndicatorDocMarker = 1
Else: RSIndicatorDocMarker = 0
End If
'CHECK THE READY STATE
If RSIndicatorClass.getattribute("data-state-busy-status") = "none" Then
RSIndicatorDataMarker = 1
Else: RSIndicatorDataMarker = 0
End If
'Compare the RSIndicators
If RSIndicatorDataMarker = 1 And RSIndicatorDocMarker = 1 Then
Else: GoTo RSIndicatorCheck
End If
End Sub
Maybe try using OnTime instead of the tight loop you currently have:
Public Sub WaitingForRS()
Dim win As Object
Dim w As Object, el, ready As Boolean, idle As Boolean
For Each w In CreateObject("Shell.Application").Windows
If w.Name Like "*Internet*" Then
If w.Title Like "Coverage user*" Then
Set win = w
Exit For
End If
End If
Next
If Not win Is Nothing Then
Set el = win.document.getelementsbyclassname("document-statetracker")(0)
ready = (el.getattribute("data-state-doc-status") = "ready")
idle = (el.getattribute("data-state-busy-status") = "none")
If ready And idle Then
ProceedWithNextSteps win 'do whatever comes next: pass in the window
Else
'wait for a while then try again
Application.OnTime Now + TimeSerial(0, 0, 1), "WaitingForRS"
End If
Else
MsgBox "Window not found!"
End If
End Sub
Might want to add a time limit so it doesn't keep looping forever if the page isn't "ready".
Check out my answer on this post Excel VBA Submitting data via IE on an online MS Forms not working
# Idea 5 subheading. The WaitForLoadSETx() function has a manual time over-ride and double loop to help catch the state.
This was the best I could do in VBA with IE object. Ideally you want to learn Selenium, PhantomJS, or Puppeteer for actual browser manipulation. There are of course cool apps, folks have built on top of these libraries to help (puppeteer recorder chrome add in)
Or to keep things in Excel, use a simple XMLHTTPRequest object to cut the browser out of the equation, and deal solely with the request / response from the web page. This is a good alternative because it lets you focus on scraping the html content, in text form without the Javascript or waiting for page to load.

Finding the default browser in VB.net

I am using Process.Start(url) to launch a URL in the default web browser and then I plan to close it using Process.Kill().
The problem is finding the default browser to know which process to kill. Suggestions?
Taken from: Opening default web browser
Private Function getDefaultBrowser() As String
Dim browser As String = String.Empty
Dim key As RegistryKey = Nothing
Try
key = Registry.ClassesRoot.OpenSubKey("HTTP\shell\open\command", False)
'trim off quotes
browser = key.GetValue(Nothing).ToString().ToLower().Replace("""", "")
If Not browser.EndsWith("exe") Then
'get rid of everything after the ".exe"
browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4)
End If
Finally
If key IsNot Nothing Then
key.Close()
End If
End Try
Return browser
End Function
There you can get the default browser. Then you can loop through the running process and kill the browser.
Dim browser As String
browser = getDefaultBrowser()
For Each p As Process In Process.GetProcesses
If p.ProcessName = browser Then
p.Kill()
Exit For
End If
Next

Programatically clicking an html button by vb.net

I have to click a HTML button programatically which is on the 3rd page of the website . The button is without id. It has just name type and value . The HTML code of the button is given below
<FORM NAME='form1' METHOD='post' action='/dflogin.php'>
<INPUT TYPE='hidden' NAME='txtId' value='E712050-15'>
<INPUT TYPE='hidden' NAME='txtassId' value='1'><INPUT TYPE='hidden' NAME='txtPsw' value='HH29'>
<INPUT TYPE='hidden' NAME='txtLog' value='0'><h6 align='right'>
<INPUT TYPE='SUBMIT' NAME='btnSub' value='Next' style='background-color:#009900; color:#fff;'></h6>
</FORM>
i am using the following code to click it
For Each webpageelement As HtmlElement In allButtons
If webpageelement.GetAttribute("value") = "Start" Then
webpageelement.InvokeMember("click")
End If
Next
But i cant able to click it . I am using the vb.net 2008 platform. Can anyone tell me the solution to click it?
Try invoking Submit on the Form rather than click on the Input.
EDIT: Oops, HTMLElementCollection does not implement the generic IEnumerable. Try this instead:
Dim l_forms = WebBrowser1.Document.GetElementsByTagName("form")
If l_forms.Count > 0 Then
l_forms.Item(0).InvokeMember("submit")
End If
Dim Elems As HtmlElementCollection
Dim WebOC As WebBrowser = WebBrowser1
Elems = WebOC.Document.GetElementsByTagName("input")
For Each elem As HtmlElement In Elems
elem.InvokeMember("click")
Next
I spent quite a while trying to find an answer to this. I never realized that you can invoke a click using javascript. Once I read that the solution becomes very easy:
Public Function clickbyid(ByVal id)
If TheBrowser.Document.GetElementById(id) IsNot Nothing Then
Dim Headers As String = "" 'insert headers if you want to
TheBrowser.Navigate("javascript:document.getElementById('" & id & "').click();", "_self", Nothing, Headers)
'This keeps the function active until the browser has finished loading
Do While TheBrowser.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
Loop
Return 1
Else
MessageBox.Show("Could not find link by id" & id)
Return Nothing
End If
End Function
You may have to change "TheBrowser" to "WebBrowser1".
If you don't want to return a result then simply change it to public sub and remove the return statements.
If the htmlelement does not have an id then use the following functions to add one
Public Function clickbyelement(ByVal theButton As HtmlElement)
Try
'Generate a unique id to identify the element
Dim randomID = "vbAdded" & GetRandom(10000, 100000).ToString
'check to make sure the ID does not already exist
While TheBrowser.Document.GetElementById(randomID) IsNot Nothing
randomID = "vbAdded" & GetRandom(10000, 100000).ToString
End While
'add the ID to the element
theButton.SetAttribute("id", randomID)
'click
clickbyid(randomID)
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
' by making Generator static, we preserve the same instance '
' (i.e., do not create new instances with the same seed over and over) '
' between calls '
Static Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max)
End Function
Thanks to Dan Tao for the random number: https://stackoverflow.com/a/2677819/381273
Tested and working!
It sounds like you are trying to do a client-side action - click the button when operating on the server (VB code). This will not work.
So, either use Javascript document.form1.submit() or call the VB sub that is connected to the button btnsub.click (or whatever you named it).
The Solution:
WebBrowser1.Navigate("UrlHere!")
'wait till the page is laoded
Do While WebBrowser1.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
Loop
WebBrowser1.Document.Body.InnerHtml = Replace(WebBrowser1.Document.Body.InnerHtml, "NAME='btnSub'", "NAME='btnSub' id='btnSub'") 'insert id into youre button
WebBrowser1.Document.GetElementById("btnSub").InvokeMember("click") 'click on btnSub
;)