等待浏览器完全加载(或从网站中提取Captcha)

时间:2014-05-11 09:59:46

标签: vb.net browser document captcha

我有一个很大的问题,我试图解决它几天,它只是没有工作。 我想创建一个程序,从网站中提取Captcha,然后将其显示给用户,用户解决它,然后程序检查代码是对还是错。

问题是“Webbrowser1_DocumenCompleted”事件不会等待,直到脚本完全加载为止。因此,有时代码显示,但有时不会......它就像50/50的机会..

到目前为止,这是我的代码:

Imports System.Text
Imports System.Text
Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    WebBrowser1.Navigate("http://minecraft-server.eu/vote/index/2421")
End Sub

Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

    Try
        Dim htmlDocument As HtmlDocument = Me.WebBrowser1.Document
        Dim htmlElementCollection As HtmlElementCollection = htmlDocument.Images
        Dim ImagesFound As Integer = 0
        For Each htmlElement As HtmlElement In htmlElementCollection
            Dim imgUrl As String = htmlElement.GetAttribute("src")
            If imgUrl.Contains("google.com/recaptcha/api/image?") Then
                ImagesFound += 1
                Select Case ImagesFound
                    Case 1
                        WebBrowser2.Navigate(imgUrl)
                End Select

            End If
        Next
    Catch ex As Exception
    End Try
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    WebBrowser1.Document.GetElementById("recaptcha_response_field").SetAttribute("value", tbText.Text)
    WebBrowser1.Document.GetElementById("minecraftname").SetAttribute("value", minecraftnamebox.text)
    WebBrowser1.Document.GetElementById("button").InvokeMember("click")
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Dim sQuelltext As String = WebBrowser1.DocumentText.ToString

    If sQuelltext.Contains("Captcha Falsch") Then
        MsgBox("Wrong verification Code! Try again.")
        Application.Restart()
    Else
        End
    End If
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Application.Restart()
End Sub
End Class

2 个答案:

答案 0 :(得分:0)

尝试检查WebBrowser1.ReadyState是否等于WebBrowserReadyState.Complete

答案 1 :(得分:0)

你的问题是可以理解的。因为浏览器不知道还有更多要执行的东西。当脚本完成加载时,并不意味着不再需要完成任何工作。可能是脚本等待200毫秒然后执行某些操作,因此没有通用的方法来确定页面何时“完全加载”。

下载整个页面时会触发DocumentCompleted事件,并且已加载所有脚本,图像和其他依赖项。因此,DocumentCompleted会在正确的时间点亮。

然而,验证码似乎是在文档完成加载后的某个时间创建的,如上所述,浏览器不知道他应该等待这个。我们可以通过访问浏览器中的页面来确认这一理论:

http://minecraft-server.eu/vote/index/2421

当浏览器隐藏旋转图标(表示加载)时,验证码实际可见大约需要500毫秒。你显然不能依赖500毫秒,因为这完全取决于连接。

WebBrowser组件确实公开了FileDownload事件,每次下载文件时都会发生这种事件。这可能是网页上的图像,任何内容。唯一的问题是,当事件触发时,无法知道事件触发的文件。

在这种情况下,最简单的解决方案是每次FileDownload事件触发时检查验证码是否已加载。在文档完全加载之前,您应该阻止在FileDownload事件中检查验证码。因此,在迭代所有HTML元素之前,请检查文档是否已完全加载。