HTML分析器允許您解析HTML並返回一個HtmlDocument。
Html Parser
Name | Description |
---|---|
From File | Loads an HTML document from a file. |
From String | Loads the HTML document from the specified string. |
From Web | Gets an HTML document from an Internet resource. |
From Browser | Gets an HTML document from a WebBrowser. |
從文件加載Html
HtmlDocument.Load
方法從文件加載HTML文檔
以下示例從文件加載Html
var path = @"test.html";
var doc = new HtmlDocument();
doc.Load(path);
var node = doc.DocumentNode.SelectSingleNode("//body");
Console.WriteLine(node.OuterHtml);
從字符串加載Html
HtmlDocument.LoadHtml
方法從指定的字符串中加載HTML文檔。
以下示例從指定的字符串加載Html。
var html = @"<!DOCTYPE html>
<html>
<body>
<h1>This is <b>bold</b> heading</h1>
<p>This is <u>underlined</u> paragraph</p>
<h2>This is <i>italic</i> heading</h2>
</body>
</html> ";
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
Console.WriteLine(htmlBody.OuterHtml);
從Web加載Html
HtmlWeb.Load
方法從Internet資源獲取HTML文檔。
以下示例從Web加載Html
var html = @"http://html-agility-pack.net/";
HtmlWeb web = new HtmlWeb();
var htmlDoc = web.Load(html);
var node = htmlDoc.DocumentNode.SelectSingleNode("//head/title");
Console.WriteLine("Node Name: " + node.Name + "\n" + node.OuterHtml);
從WebBrowser加載Html
HtmlWeb.Load
方法從Web瀏覽器獲取HTML文檔。 通過自定義isBrowserScriptCompleted
參數,可以等待JavaScript運行。
以下示例從WebBrowser
加載Html並等待,直到文本被設置爲DIV。
string url = "http://html-agility-pack/from-browser";
var web1 = new HtmlWeb();
var doc1 = web1.LoadFromBrowser(url, o =>
{
var webBrowser = (WebBrowser) o;
//等待直到動態文本被設置
return !string.IsNullOrEmpty(webBrowser.Document.GetElementById("uiDynamicText").InnerText);
});
var t1 = doc1.DocumentNode.SelectSingleNode("//div[@id='uiDynamicText']").InnerText;
var web2 = new HtmlWeb();
var doc2 = web2.LoadFromBrowser(url, html =>
{
//等待直到動態文本被設置
return !html.Contains("<div id=\"uiDynamicText\"></div>");
});
var t2 = doc2.DocumentNode.SelectSingleNode("//div[@id='uiDynamicText']").InnerText;
Console.WriteLine("Text 1: " + t1);
Console.WriteLine("Text 2: " + t2);