等待浏览器完全加载(或从网站提取验证码)



我有一个大问题,我试图修复它的天,它只是不工作。我想做一个程序,从一个网站提取验证码,然后显示给用户,用户解决它,然后程序检查代码是否正确或错误。

问题是,事件"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

你的问题可以理解。因为浏览器不知道还有更多的东西要执行。当脚本完成加载时,并不意味着没有更多的工作要做。它可能是一个脚本等待200毫秒,然后做一些事情,所以没有通用的方法来确定一个页面何时"完全加载"。

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

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

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

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

WebBrowser组件公开FileDownload事件,该事件在每次下载文件时发生。这可以是网页上的图片,任何东西。唯一的问题是,当事件触发时,没有办法知道事件为哪个文件触发。

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

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

最新更新