I am learning about automated interactions with HtmlElements on a Webbrowser. In this example, I am entering a search string into the textbox and then clicking the search button. Once that goes through, I automate a second search.
Each time I open the form it correctly navigates to Google and inserts the search string into the Google's search box... but the button click only works about half the time. Every other time I open the form it never clicks the button and performs the search. Why could this be happening?
Imports System.Text.RegularExpressions
Public Class frmGoogleTest
Private Sub webGoogleTest_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles webGoogleTest.DocumentCompleted
'When Google is loaded, perform the first search
If Regex.IsMatch(webGoogleTest.Url.AbsoluteUri, Regex.Escape("https://www.google.com/?gws_rd=ssl"), RegexOptions.IgnoreCase) Then
webGoogleTest.Document.All.GetElementsByName("q")(0).SetAttribute("value", "first search")
webGoogleTest.Document.All("btnK").InvokeMember("click")
'Second search
ElseIf Regex.IsMatch(webGoogleTest.Url.AbsoluteUri, Regex.Escape("&q=first+search"), RegexOptions.IgnoreCase) Then
webGoogleTest.Document.All.GetElementsByName("q")(0).SetAttribute("value", "second search")
webGoogleTest.Document.All("btnK").InvokeMember("click")
End If
End Sub
Private Sub frmGoogleTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Go to Google when the form opens
webGoogleTest.Navigate("http://www.google.com")
End Sub
End Class