I have written some code in VB.NET which 'grabs' the src/URL of an image based on its 'alt' attribute. It works perfectly on some sites, but on others it requires threading - to wait until the images have loaded, because the images have not loaded by the time the DocumentCompleted occurs.
My problem is that when my code is used with threading, I get an invalidcastexception
error.
Here is my code, and where the error occurs:
Private Sub WB1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WB1.DocumentCompleted
urlBox.Text = e.Url.ToString()
If urlBox.Text = "URL_GOES_HERE"
Dim success As Integer = site.fill() 'calls another function, returns 1 on success
If success = 1 Then
Dim captchaThread As New Thread(New ThreadStart(AddressOf getCaptchaURL))
captchaThread.Start()
End If
End If
End Sub
Public Function getCaptchaURL()
Thread.Sleep(5000) 'Tell thread to sleep so images can load
Dim URL As String
Dim images As HtmlElementCollection = WB1.Document.GetElementsByTagName("img") 'This is where I get the 'invalidcastexception' error
For Each element As HtmlElement In images
Dim source As String = element.GetAttribute("alt").ToString
If source = "CAPTCHA Image" Then
URL = element.GetAttribute("src")
MessageBox.Show(URL) 'Show URL to check the source has been grabbed
End If
Next
Return URL 'Return URL for further functions
End Function
So, to clarify, this code: Dim images As HtmlElementCollection = WB1.Document.GetElementsByTagName("img")
gives me an error when used with threads, but doesn't when not used in threads.