栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用.NET的WebBrowser或mshtml.HTMLDocument动态生成HTML代码?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用.NET的WebBrowser或mshtml.HTMLDocument动态生成HTML代码?

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

  • 严格来说,不一定总能确定页面何时以100%的概率完成渲染。有些页面非常复杂,并使用连续的AJAX更新。但是,通过轮询页面的当前HTML快照以查找更改并检查

    WebBrowser.IsBusy
    属性,我们可以非常接近。这就是
    LoadDynamicPage
    下面的内容。

  • 在页面上方永无休止的情况下,必须在上面加上一些超时逻辑(请注意

    CancellationTokenSource
    )。

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

  • 使用浏览器功能控件启用HTML5呈现非常重要,因为

    WebBrowser
    默认情况下,该功能以IE7仿真模式运行。这就是
    SetFeatureBrowserEmulation
    下面的内容。

  • 这是一个WinForms应用程序,但是可以轻松地将该概念转换为控制台应用程序。

  • 此逻辑在您专门提到的URL上很好用:

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_USERSoftwareMicrosoftInternet ExplorerMainFeatureControlFEATURE_BROWSER_EMULATION",     appName, 10000, RegistryValueKind.DWord);        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/514663.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号