如何使用.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.HTMLDocumentmshtml.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>
以上是使用 .NET 動態產生 HTML 程式碼的方法有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!