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