【问题标题】:capture web page content wpf web browser捕获网页内容 wpf 网络浏览器
【发布时间】:2013-01-06 00:09:06
【问题描述】:

我想以编程方式(WPF、C#)登录我的财务账户网站 (https) 并检索我的一些账户数据。因为该站点使用 cookie 和其他会话验证,我认为最好的方法是使用 Web 浏览器控件,而不是 httpWebRequest。我似乎无法捕捉屏幕内容。

我能够使用 winforms 成功地做到这一点,但我想在 WPF 中做到这一点。这是来自 winforms 项目的代码 sn-p:

webBrowser1.Navigate( @"https://myfinancialaccountURL" );
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(
                                                      wb1DocumentCompleted );

private void wb1DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e )
{
    string wb1LogonScreen = webBrowser1.DocumentText;

    --- process the data, etc.  ---
}

这是来自 WPF 尝试的代码 sn-p:

webBrowser1.Navigated += new NavigatedEventHandler( webBrowser1_Navigated );
webBrowser1.Navigate( @"https:myfinancialaccountURL" );

我对 WPF Web 浏览器控件进行了广泛研究,它有一个 Document 属性,但我不知道如何获取内容(或内部文本)。

我对此进行了研究,但仍然无法找到答案。请告诉我是否需要提供更多信息。我将非常感谢您的帮助。

感谢

【问题讨论】:

    标签: wpf browser webpage


    【解决方案1】:

    您可以将 Document 属性作为 MSHTML.Document 读取,然后使用它来获取文本。您需要在项目中包含 Microsoft.mshtml 库。

      mshtml.HTMLDocument doc = null;
            string docState = string.Empty;
    
           // CODE TO ENSURE THAT THE DOCUMENT AND THE SCRIPTS HAVE LOADED
            Action getDocState = () =>
            {
                doc = wb.Document as mshtml.HTMLDocument;
                if (null != doc)
                {
                    docState = doc.readyState;
                }
            };
    
            App.Current.Dispatcher.Invoke(
                        DispatcherPriority.Normal,
                        getDocState);
    
    
            if (null != doc)
            {
                while ((docState != "complete") && (docState != "interactive"))
                {
                    // It should not take more than one or two iterations for the document to get loaded.
                    Thread.Sleep(100);
                    App.Current.Dispatcher.Invoke(
                        DispatcherPriority.Normal,
                        getDocState);
                    }
                }
           // DOC SHOULD BE LOADED AND READABLE NOW
    
                // Go back to the UI thread to get more details
                if (!App.Current.Dispatcher.HasShutdownStarted)
                {
                   // This line is of your interest here
                    MessageBox.Show(doc.documentElement.innerHTML);
                }
            }
    

    编辑:您可以在导航事件处理程序中使用此代码。我等待文档加载代码的原因是,一旦 WPF 加载/导航完成,Web 浏览器就会加载 HTML 和脚本等。此脚本可确保文档已完全加载并处于可以交互的状态它。

    【讨论】:

    • 谢谢。我会试一试并报告结果。
    • 我知道这个答案从未被提问者选择过,但我只是尝试过,它有效!
    猜你喜欢
    • 2012-12-23
    • 1970-01-01
    • 2012-07-24
    • 2012-09-03
    • 2012-08-07
    • 1970-01-01
    • 2012-10-30
    • 2014-08-10
    • 2015-12-31
    相关资源
    最近更新 更多