摘要
在開發過程中,很有可能會遇到這樣的情況,服務端返回的是html的內容,但需要在客戶端顯示純文本內容,這時候就需要解析這些html,拿到里面的純文本。達到這樣的目的可以有很多途徑,比如自己寫正則表達式,但對於沒有什么規則的內容,就有點力不從心了。Html Agility Pack開源組件,可以通過xPath的方式快速的解析html內容。
一個例子
組件網址:http://htmlagilitypack.codeplex.com/ ,你可以通過Nuget進行安裝。
比如我們這里解析博客園首頁文章列表,查看博客園首頁列表html,如圖所示:
抓取所有文章的名稱
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HtmlAgilityPack; namespace HtmlAgilityPackDemo { class Program { static void Main(string[] args) { //初始化網絡請求客戶端 HtmlWeb webClient = new HtmlWeb(); //初始化文檔 HtmlDocument doc = webClient.Load("http://www.cnblogs.com/"); //查找節點 HtmlNodeCollection titleNodes = doc.DocumentNode.SelectNodes("//a[@class='titlelnk']"); if (titleNodes != null) { foreach (var item in titleNodes) { Console.WriteLine(item.InnerText); } } Console.Read(); } } }
輸出
記得之前自己寫過一個小工具,當時還是自己寫的正則來匹配的,和這個組件相比確實很麻煩。
在上面的代碼中,有[@class='xxx']的設置,它是根據html標簽的屬性查找node,當然你也可以進行其它的設置,如根據id查找,你可以這樣寫h3[@id='xxxx']。
獲取節點的內容,可以通過下面的方式獲取
node.InnerText
node.InnerHtml
node.OuterHtml