【问题标题】:Wait for internet explorer to load everything?等待 Internet Explorer 加载所有内容?
【发布时间】:2017-02-01 17:21:57
【问题描述】:

我正在抓取一个网页,并等待 Internet Explorer 完成加载,但由于某种原因它不是。我试图在页面上获取一个值,但等待部分没有等待,因此当应该有一个值时该值返回空白。 IE 页面已加载完毕,但页面上元素的值尚未加载。 有没有办法等待所有元素完成加载后再继续执行下一行代码?这是我的代码:

Dim IE As Object 
Dim myvalue as string

IE = CreateObject("internetexplorer.application")
IE.navigate("mypage")

While Not IE.ReadyState = WebBrowserReadyState.Complete
    Application.DoEvents()
End While

myValue = IE.document.getElementById("theValue").getAttribute("value")
Debug.Print(myValue)

【问题讨论】:

  • 只是一个想法,但您是否首先确认您可以转到此页面并使用大多数浏览器具有 F12 的内置调试器?您可以通过这种方式直接测试 javascript: "document.getElementById("theValue").getAttribute("value")" 并确保它是正确的。
  • 首先不要使用Application.DoEvents()来保持你的UI响应!这是不好的做法!请阅读:Keeping your UI Responsive and the Dangers of Application.DoEvents.
  • @djangojazz 是的,该值是在 Internet Explorer 完成加载后加载的,因此它会跳过 myValue 部分而没有获得实际值。
  • 既然您显然在使用 WinForms,请创建一个 .NET 的 WebBrowser control 实例并改为订阅其 DocumentCompleted event
  • 我喜欢,但是浏览器在访问网页时会发出警报,我已经在浏览器上关闭了它们等等,但这给我带来了麻烦,因此我正朝着这个方向前进。我可以暂停程序 5 秒,但如果不需要,我不想等待整个 5 秒。

标签: vb.net web-scraping


【解决方案1】:

不应使用Application.DoEvents() 以保持您的用户界面响应!我真的不能强调这一点!经常使用它是一种糟糕的技巧,只会产生比它解决的问题更多的问题。

更多信息请参考:Keeping your UI Responsive and the Dangers of Application.DoEvents

正确的方法是使用InternetExplorer.DocumentComplete event,它会在页面(或其子部分,例如iframe)完全加载时引发。以下是如何使用它的简短示例:

  1. Solution Explorer 中右键单击您的项目,然后按Add Reference...

  2. 转到COM 选项卡,找到名为Microsoft Internet Controls 的参考,然后按OK

  3. SHDocVw 命名空间导入到您要使用它的文件中,并创建一个 InternetExplorer 类型的类级别 WithEvents 变量,以便您可以使用 @987654324 订阅事件@。

还有瞧!

Imports SHDocVw

Public Class Form1

    Dim WithEvents IE As New InternetExplorer

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        IE.Navigate("http://www.google.com/")
    End Sub

    Private Sub IE_DocumentComplete(pDisp As Object, ByRef URL As Object) Handles IE.DocumentComplete
        MessageBox.Show("Successfully navigated to: " & URL.ToString())
    End Sub
End Class

或者,您也可以使用lambda expression 在线订阅事件:

Imports SHDocVw

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim IE As New InternetExplorer
        IE.Navigate("http://www.google.com/")

        AddHandler IE.DocumentComplete, Sub(pDisp As Object, ByRef URL As Object)
                                            MessageBox.Show("Successfully navigated to: " & URL.ToString())
                                        End Sub
    End Sub
End Class

【讨论】:

  • @pokemon_Man :这很快,你确定在接受之前用你的代码正确测试了吗?
猜你喜欢
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多