我已经在vb.net中编写了一些代码,这些代码'抓取'图像的src/url基于其'alt'属性。它可以在某些站点上完美工作,但是在其他站点上,它需要线程 - 等待直到加载图像,因为图像在发生记录结束时没有加载。
。我的问题是,当我的代码用于线程时,我会收到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
so,为了澄清,此代码:Dim images As HtmlElementCollection = WB1.Document.GetElementsByTagName("img")
在与线程一起使用时给我一个错误,但在线程中不使用时不使用。
行
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