【问题标题】:Valid way to return HTMLDocument while cleaning InternetExplorer instance清理 InternetExplorer 实例时返回 HTMLDocument 的有效方法
【发布时间】:2020-12-18 13:56:04
【问题描述】:

这是在清理我的 InternetExplorer 实例时返回 HTMLDocument 的有效方法吗?

Private Function myFunction() As HTMLDocument

    'init
    Dim out As HTMLDocument
    Dim browser As InternetExplorer
    Set browser = CreateObject("InternetExplorer.Application")

    ...
        
    'get HTMLDocument
    Set out = browser.document

    browser.Quit
    Set browser = Nothing

    Set myfunction = out
Exit Function

我之所以这么问,是因为稍后在我的代码中使用返回的 HTMLDocument 会出现不稳定的行为。我会看到输出003,但不会看到004

doc = myFunction()
...
Debug.Print "003"
strVar = doc.getElementsByClassName("sectionheading_center")(0).innerText
Debug.Print "004"
....

错误:-2147417848-Automation error The object invoked has disconnected from its clients. -VBAProject-1000440-0

【问题讨论】:

  • 不像这样,因为您正在发布浏览器参考。创建一个包装类,在其中实例化 Intitialize() 上的浏览​​器并清除 Terminate()

标签: excel vba internet-explorer


【解决方案1】:

您将失去动态交互,但可以通过将 innerHTML 传输到 MSHTML.HTMLDocument 变量来获取 html。它也只是正文 html。

Private Function myFunction() As MSHTML.HTMLDocument
    'init
    Dim out As MSHTML.HTMLDocument
    Dim browser As SHDocVw.InternetExplorer
    Set browser = New SHDocVw.InternetExplorer

    '...Other code
        
    'get HTMLDocument
    Set out = New MSHTML.HTMLDocument
    out.body.innerHTML = browser.Document.innerHTML

    browser.Quit
    Set myFunction = out
Exit Function

@KostasK 的类解决方案是维护实例化实例以及向该对象添加方法的好方法。

【讨论】:

  • 我想知道是否通过像我们正在讨论的那样传输 innerHTML,DOM 的解析方式是否与 IE 实例不同?我使用 IE 是因为当我使用 ServerHTTP 或 XMLHTTP 时,我的一部分用户群在使用 HTMLDocument 进行解析时会得到不同的结果。
  • 您正在从 ie.document 传输,因此您将在传输时根据 ie.document.body 获得 document.body.innerHTML。如果您想要 ie html 解析器,而不是 HTMLDocument DOM 解析器,那么只需转回 ie.document.body 即可。如果这确实是您想要的,那么使用类是迄今为止更好的方法,然后传递 ie 实例。请注意,这两种情况都有 document.mode/emulations 影响解析。
  • 刚刚注意到,您的示例中的“SHDocVw”是什么?
  • 上课了。使用其父类限定 Internet Explorer 对象的良好做法。
  • 我同意 QHarr 的建议。他的解决方案可以帮助您解决问题。你可以在你身边测试它。如果仍然如此,您会得到不同的结果,那么我建议您分享源代码。它可以帮助我们重现问题。测试结果有助于正确理解问题并有助于缩小问题范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
相关资源
最近更新 更多