0

我在 VB.NET 中编写了一些代码,这些代码根据其“alt”属性“抓取”图像的 src/URL。它在某些站点上完美运行,但在其他站点上需要线程 - 等待图像加载,因为在 DocumentCompleted 发生时图像尚未加载。

我的问题是当我的代码与线程一起使用时,我得到一个invalidcastexception错误。

这是我的代码,以及发生错误的位置:

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

因此,为了澄清,这段代码:Dim images As HtmlElementCollection = WB1.Document.GetElementsByTagName("img")与线程一起使用时给我一个错误,但在线程中不使用时不会。

4

1 回答 1

0

线

For Each element As HtmlElement In images

需要重写以避免遇到转换类型的问题。

尝试以下操作:

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

         'the rest of your code goes here

   End If
Next
于 2012-11-03T11:57:45.483 回答