Use WebBrowser or MSHTML to dynamically generate HTML code in C#
This article will explore two different methods to generate HTML code:
1. Use System.Windows.Forms.WebBrowser class
This method is simple, but it also has limitations. To retrieve the HTML code of a web page:
<code class="language-csharp">[STAThread] public static void Main() { WebBrowser wb = new WebBrowser(); wb.Navigate("https://www.example.com/"); wb.DocumentCompleted += (sender, e) => { mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)wb.Document.DomDocument; foreach (IHTMLElement element in doc.all) { Console.WriteLine(element.outerHTML); } }; Application.Run(wb); }</code>
This code navigates to the specified URL and once the document is loaded, it iterates over the DOM elements to extract the HTML code.
However, this approach has disadvantages: it is slow, sometimes fails to retrieve the full HTML, and is not suitable for dynamic web pages using AJAX calls.
2. Use mshtml.HTMLDocument interface
This method uses the mshtml.HTMLDocument interface in the Microsoft HTML Object Library assembly. It includes:
<code class="language-csharp">public static void Main() { mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)new mshtml.HTMLDocument(); doc.write(new System.Net.WebClient().DownloadString("https://www.example.com/")); foreach (IHTMLElement element in doc.all) { Console.WriteLine(element.outerHTML); } }</code>
This code downloads the HTML code of the web page, loads it into an HTML document, and iterates over the DOM elements to extract the HTML code.
Important Notes:
The above is the detailed content of How to Dynamically Generate HTML Code in C# Using WebBrowser or MSHTML?. For more information, please follow other related articles on the PHP Chinese website!