12

我读过的有关此主题的大多数答案都指向 System.Windows.Forms.WebBrowser 类或 Microsoft HTML 对象库程序集中的 COM 接口 mshtml.HTMLDocument。

WebBrowser 类并没有把我带到任何地方。以下代码无法检索我的 Web 浏览器呈现的 HTML 代码:

[STAThread]
public static void Main()
{
    WebBrowser wb = new WebBrowser();
    wb.Navigate("https://www.google.com/#q=where+am+i");

    wb.DocumentCompleted += delegate(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)wb.Document.DomDocument;
        foreach (IHTMLElement element in doc.all)
        {
                    System.Diagnostics.Debug.WriteLine(element.outerHTML);
        }     
    };
    Form f = new Form();
    f.Controls.Add(wb);
    Application.Run(f);
} 

以上只是一个例子。我对找到一种解决方法来找出我所在城镇的名称并不感兴趣。我只需要了解如何以编程方式检索那种动态生成的数据。

(调用 new System.Net.WebClient.DownloadString(" https://www.google.com/#q=where+am+i "),将结果文本保存在某处,搜索您当前所在城镇的名称找到了,如果你能找到它,请告诉我。)

但是,当我从 Web 浏览器(即或 firefox)访问“ https://www.google.com/#q=where+am+i ”时,我看到网页上写着我所在城镇的名称。在 Firefox 中,如果我右键单击城镇名称并选择“Inspect Element (Q)”,我会清楚地看到用 HTML 代码编写的城镇名称,这看起来与 WebClient 返回的原始 HTML 完全不同.

在我玩腻了 System.Net.WebBrowser 之后,我决定试一试 mshtml.HTMLDocument,只是为了得到同样无用的原始 HTML:

public static void Main()
{
    mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)new mshtml.HTMLDocument();
    doc.write(new System.Net.WebClient().DownloadString("https://www.google.com/#q=where+am+i"));

    foreach (IHTMLElement e in doc.all)
    {
            System.Diagnostics.Debug.WriteLine(e.outerHTML);
    }
} 

我想必须有一种优雅的方式来获取这种信息。现在我能想到的就是在表单中添加一个 WebBrowser 控件,让它导航到有问题的 URL,发送键“CLRL,A”,然后将页面上显示的任何内容复制到剪贴板并尝试解析它。不过,这是一个可怕的解决方案。

4

2 回答 2

19

我想为Alexei 的回答贡献一些代码。几点:

  • 严格来说,可能并不总是能够以 100% 的概率确定页面何时完成渲染。有些页面非常复杂,并且使用持续的 AJAX 更新。但是我们可以通过轮询页面的当前 HTML 快照以进行更改并检查WebBrowser.IsBusy属性来非常接近。这就是 LoadDynamicPage下面的内容。

  • 一些超时逻辑必须存在于上述之上,以防页面呈现永无止境(注CancellationTokenSource)。

  • Async/await是一个很好的编码工具,因为它为我们的异步轮询逻辑提供了线性代码流,这大大简化了它。

  • 使用Browser Feature Control启用 HTML5 渲染很重要,因为WebBrowser默认情况下在 IE7 仿真模式下运行。这就是SetFeatureBrowserEmulation下面的内容。

  • 这是一个 WinForms 应用程序,但这个概念可以很容易地转换成一个控制台应用程序

  • 此逻辑适用于您特别提到的 URL:https://www.google.com/#q=where+am+i

using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WbFetchPage
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            SetFeatureBrowserEmulation();
            InitializeComponent();
            this.Load += MainForm_Load;
        }

        // start the task
        async void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                var cts = new CancellationTokenSource(10000); // cancel in 10s
                var html = await LoadDynamicPage("https://www.google.com/#q=where+am+i", cts.Token);
                MessageBox.Show(html.Substring(0, 1024) + "..." ); // it's too long!
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        // navigate and download 
        async Task<string> LoadDynamicPage(string url, CancellationToken token)
        {
            // navigate and await DocumentCompleted
            var tcs = new TaskCompletionSource<bool>();
            WebBrowserDocumentCompletedEventHandler handler = (s, arg) =>
                tcs.TrySetResult(true);

            using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
            {
                this.webBrowser.DocumentCompleted += handler;
                try 
                {           
                    this.webBrowser.Navigate(url);
                    await tcs.Task; // wait for DocumentCompleted
                }
                finally
                {
                    this.webBrowser.DocumentCompleted -= handler;
                }
            }

            // get the root element
            var documentElement = this.webBrowser.Document.GetElementsByTagName("html")[0];

            // poll the current HTML for changes asynchronosly
            var html = documentElement.OuterHtml;
            while (true)
            {
                // wait asynchronously, this will throw if cancellation requested
                await Task.Delay(500, token); 

                // continue polling if the WebBrowser is still busy
                if (this.webBrowser.IsBusy)
                    continue; 

                var htmlNow = documentElement.OuterHtml;
                if (html == htmlNow)
                    break; // no changes detected, end the poll loop

                html = htmlNow;
            }

            // consider the page fully rendered 
            token.ThrowIfCancellationRequested();
            return html;
        }

        // enable HTML5 (assuming we're running IE10+)
        // more info: https://stackoverflow.com/a/18333982/1768303
        static void SetFeatureBrowserEmulation()
        {
            if (LicenseManager.UsageMode != LicenseUsageMode.Runtime)
                return;
            var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
                appName, 10000, RegistryValueKind.DWord);
        }
    }
}
于 2014-01-05T14:10:34.963 回答
5

您的网络浏览器代码看起来很合理 - 等待获取当前内容的内容。不幸的是,没有来自浏览器或 JavaScript 的官方“我已经执行完 JavaScript,请随意窃取内容”的通知。

某种类型的主动等待(不是Sleep但是Timer)可能是必要的并且是特定于页面的。即使您使用无头浏览器(即 PhantomJS),您也会遇到同样的问题。

于 2014-01-05T05:33:03.723 回答