首頁 > web前端 > js教程 > 主體

使用 .NET 動態產生 HTML 程式碼的方法有哪些?

Mary-Kate Olsen
發布: 2024-10-18 08:32:29
原創
727 人瀏覽過

What are the Approaches to Dynamically Generate HTML Code Using .NET?

如何使用.NET和WebBrowser或mshtml.HTMLDocument動態生成HTML代碼

簡介

使用.NET 動態產生HTML 程式碼提供了對網頁內容的靈活性和控制。本文探討了兩種擷取動態 HTML 程式碼的方法:利用 System.Windows.Forms 中的 WebBrowser 類別和利用 Microsoft HTML 物件庫程式集中的 COM 介面 mshtml.HTMLDocument。

方法 1:利用WebBrowser

WebBrowser 類別是載入網頁和存取其內容的便利選項。以下程式碼示範如何使用 WebBrowser DocumentCompleted 事件載入頁面並擷取其 HTML:

<code class="csharp">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);
    }     
};</code>
登入後複製

方法 2:使用 mshtml.HTMLDocument

mshtml.HTMLDocument

<code class="csharp">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);
}</code>
登入後複製

mshtml.HTMLDocument

mshtml.HTMLDocument

mshtml.HTMLDocument

mshtml.HTMLDocument

<code class="csharp">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;
        }

        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);
            }
        }

        async Task<string> LoadDynamicPage(string url, CancellationToken token)
        {
            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;
                }
            }

            var documentElement = this.webBrowser.Document.GetElementsByTagName("html")[0];

            var html = documentElement.OuterHtml;
            while (true)
            {
                await Task.Delay(500, token); 

                if (this.webBrowser.IsBusy)
                    continue; 

                var htmlNow = documentElement.OuterHtml;
                if (html == htmlNow)
                    break; 

                html = htmlNow;
            }

            token.ThrowIfCancellationRequested();
            return html;
        }

        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);
        }
    }
}</code>
登入後複製
mshtml.HTMLDocument

mshtml.HT.html.html 檔案。 HTMLDocument 介面提供了與 HTML 文件互動的直接方式。您可以使用它從字串載入和存取HTML:WebBrowser 和mshtml.HTMLDocument 的限制WebBrowser 和mshtml.HTMLDocument 方法都可能不會總是傳回完全呈現的HTML 程式碼。為了解決這個問題,提供了一種使用非同步/等待和取消令牌的改進方法作為參考內容中的增強回應。此方法動態監視 HTML 變更並在完全呈現時檢索內容。 程式碼範例以下最佳化程式碼示範了改進的方法:此程式碼可確保在擷取HTML 內容之前頁面已完全呈現,從而獲得更準確可靠的結果。

以上是使用 .NET 動態產生 HTML 程式碼的方法有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!