HtmlAgilityPack的简单使用
生活随笔
收集整理的這篇文章主要介紹了
HtmlAgilityPack的简单使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
HtmlAgilityPack可以對Html進行解析,獲取某個標簽的屬性的值、InnerText、InnerHtml等,還可以去除js代碼,css樣式和注釋。
using HtmlAgilityPack;HtmlDocument htmlDocContent = new HtmlDocument(); htmlDocContent.LoadHtml(strHtmlContent); htmlDocContent.DocumentNode為這段Html的根標簽,它的ChildNodes屬性為其子標簽。比如,要獲取這段Html中所有的img的src屬性的值,和每個標簽的InnerText,可以通過遞歸獲取 StringBuilder sbContent = new StringBuilder();if (node.ChildNodes.Count < 1){if (node.InnerText.IsNotNullOrEmpty()){sbContent.AppendLine(string.Concat("<txt>", node.InnerText, "</txt>"));}if (string.Equals(node.Name, "img", StringComparison.InvariantCultureIgnoreCase) && node.Attributes.Contains("src")){sbContent.AppendLine(string.Concat("<img>", FormatHtml.GetFullImageUrl(node.Attributes["src"].Value, siteUrl), "</img>"));}return sbContent.ToString();}foreach (HtmlNode childNode in node.ChildNodes){sbContent.Append(FormatHtml.GetContent(childNode, siteUrl));}return sbContent.ToString();
如果這段html中只有一個標簽或者有多個同級標簽,那么HtmlAgilityPack會自動生成一個根標簽。
HtmlAgilityPack還可以處理js代碼,css樣式和注釋
foreach (HtmlNode nodeScripte in node.Descendants("script").ToList()){nodeScripte.Remove();}foreach (HtmlNode nodeStyle in node.Descendants("style").ToList()){nodeStyle.Remove();}foreach (HtmlNode nodeComment in node.Descendants("//comment()").ToList()){nodeComment.Remove();}?
轉載于:https://www.cnblogs.com/dc-lancer/archive/2013/03/27/2985163.html
總結
以上是生活随笔為你收集整理的HtmlAgilityPack的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑马程序员-面向对象-06天-5(单例设
- 下一篇: 基于UDP的组播网络程序