0

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.

jonsca
  • 10,218
  • 26
  • 54
  • 62
1mmortal
  • 23
  • 3

1 Answers1

0

The line

For Each element As HtmlElement In images

needs to be re-written to avoid running into problems of casting types.

Try the following:

For Each element In images
   If TypeOf(element) Is HtmlElement Then

         'the rest of your code goes here

   End If
Next
Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • I'll check as soon as possible, as it stands the site is giving me an error based on the fact i have visited it too frequently recently :/ Thanks a lot [EDIT] I'm still getting the same InvalidCastExcpetion was unhandled on the same line of code, even when using the alternate for loop. – 1mmortal Nov 03 '12 at 12:05
  • Still an error, using: "If TypeOf(element) Is HtmlElement Then" – 1mmortal Nov 03 '12 at 12:11
  • I've now been told that "Cross thread calls are not allowed. You need to use a delegate.", so i will look into that. Thanks anyway – 1mmortal Nov 03 '12 at 12:13
  • More specifically, i get the "Specified cast is not valid." exception – 1mmortal Nov 03 '12 at 12:23