【问题标题】:Error when trying to access DOM using SHDocVw.InternetExplorer.Document尝试使用 SHDocVw.InternetExplorer.Document 访问 DOM 时出错
【发布时间】:2012-01-18 05:31:37
【问题描述】:

我可以看到这是一个简单的更正,但它让我很难过。

这是我遇到的错误

COMException 未处理

对 COM 组件的调用已返回错误 HRESULT E_FAIL。

这是代码(我已经删除了 URL,但它们是有效的)

class SMSHandler
{
    private InternetExplorer ie;
    private object URL = "##########";
    private object URL2 = "###########";

    public SMSHandler()
    {
        ie = new InternetExplorer();
        ie.Visible = true;
    }

    public void openMACS()
    {
        object Empty = 0;

        ie.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty);

        while (ie.Busy);

        ie.Navigate2(ref URL2, ref Empty, ref Empty, ref Empty, ref Empty);

        IHTMLDocument2 HTMLDoc = (IHTMLDocument2)ie.Document;

    }

这是产生错误的行

IHTMLDocument2 HTMLDoc = (IHTMLDocument2)ie.Document;

网页可以正常打开,但是当我尝试将文档分配给 IHTMLDocument2 时它失败了。

任何帮助都会很棒

【问题讨论】:

    标签: c# dom


    【解决方案1】:

    您忘记等待页面加载完成。 while (ie.Busy) ;循环非常难看,您不想在等待 IE 完成时烧毁 100% 核心。请改用 DocumentComplete 事件。还有一个状态机来跟踪你的位置。像这样的:

    private int state = 0;
    public SMSHandler()
    {
        ie = new InternetExplorer();
        ie.DocumentComplete += ie_DocumentComplete;
        ie.Visible = true;
    }
    
    void ie_DocumentComplete(object pDisp, ref object URL) {
        object Empty = 0;
        if (state == 1) {
            ie.Navigate2(ref URL2, ref Empty, ref Empty, ref Empty, ref Empty);
            state++;
        }
        else if (state == 2) {
            IHTMLDocument2 HTMLDoc = (IHTMLDocument2)ie.Document;
            // etc..
            state = 0;
        }
    }
    
    public void openMACS()
    {
        object Empty = 0;
        state = 1;
        ie.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty);
    }
    

    考虑使用 WebBrowser 类,这样您就不必在进程外运行 IE。 This answer 向您展示了如何在单独的线程中运行它。这很可能是您的代码出现 E_FAIL 的原因。

    【讨论】:

    • 感谢您的帮助,看来我可以修改我的需求
    【解决方案2】:

    代码对我来说在本地工作,但我会为你破解。

    看看ie.Document 类型。对我来说,它返回实现了IHTMLDocument2 接口的mshtml.HTMLDocumentClass。也许您没有引用适当的 DLL。我假设您手动添加了 SHDocVw.dllmshtml 引用?

    另外,请检查您的时间安排。投射文档时我有E_FAIL,但导航不完整。所以你需要等待才能执行演员表。

    【讨论】:

      猜你喜欢
      • 2012-07-06
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 2011-11-26
      相关资源
      最近更新 更多