標籤:c# xml html Regex
HTML Parser
一個比較方便的html解析package是HtmlAgilityPack,可以按照如顯示在Visual Studio中安裝。
使用該包的一個簡單一實例代碼如下:
public static bool CrawlCategoryReviewInfo(string categoryUrl) { var resp = HttpUtils.GetResponseData(categoryUrl); if (resp == null) { logger.Info("Failed to request the category page from Suning server!"); return false; } HtmlDocument document = new HtmlDocument(); document.LoadHtml(resp); HtmlNodeCollection collection = document.DocumentNode.SelectNodes("//div[@id=‘productTab‘]//li[contains(@class,‘item‘)]"); if (collection == null || collection.Count < 1) return false; foreach(HtmlNode prod in collection) { if (prod == null || prod.Attributes["name"] == null) continue; string prodId = prod.Attributes["name"].Value; if(prodId.StartsWith("000000000")) prodId = prodId.Substring(9); HtmlNode commentNode = prod.SelectSingleNode(".//a[contains(@name,‘comment‘)]/i"); if (commentNode == null) continue; int commentCount = int.Parse(commentNode.InnerText); Console.WriteLine(prodId + "\t" + commentCount); } if (collection.Count < int.Parse(ConfigurationManager.AppSettings["CAT_PAGE_ITEM_NUM"])) return false; return true; }
需要特別注意的是,對於在HtmlNode內部找子HtmlNode所寫的xpath,xpath需要在前面加上”.”,如上面的”.//a[contains(@name,’comment’)]/i”,否則可能會發現找的是全域的Node。
XML DOM
系統空間System.Xml.Linq中的XDocument可以協助解析或者輸出XML檔案。
1) 載入解析XML:
var filePath = Path.Combine(path, "image_status.xml"); XDocument doc = XDocument.Load(filePath); var pics = doc.Descendants("pic"); foreach (var pic in pics) { string url = (string)pic.Element("url"); string imgFile = (string)pic.Element("file"); processedImages.Add(url, imgFile); }
2) 儲存產生XML
var filePath = Path.Combine(path, "image_status.xml"); var docUpdate = new XElement("status"); foreach (var tuple in processedImages) { var item = new XElement("image"); item.Add(new XElement("url", tuple.Key)); item.Add(new XElement("file", tuple.Value)); docUpdate.Add(item); } docUpdate.Save(filePath);
Regex抽取
利用Regex來抽取資訊,其實不同語言的邏輯都一樣,文法略有不同。這裡不做介紹,僅僅給出一個抽取的例子作為參考。注意每一個匹配部分會用”?<—>”開頭來對該Group命名,後面取匹配的資料的時候就可以藉助這個名字得到相應的匹配值。
public static void CrawlProductReviewInfo() { string resp = "satisfy({\"reviewCounts\":[{\"oneStarCount\":2,\"twoStarCount\":0,\"threeStarCount\":23,\"fourStarCount\":43,\"fiveStarCount\":431,\"againCount\":4,\"bestCount\":0,\"picFlagCount\":5,\"totalCount\":499,\"qualityStar\":4.8}],\"returnCode\":\"1\",\"returnMsg\":\"成功擷取評價個數\"})"; Regex revRegex = new Regex("\"totalCount\":(?<comment>.*?),\"qualityStar\":(?<score>.*?)}"); MatchCollection mc = revRegex.Matches(resp); if (mc.Count > 0) { var comment = decimal.Parse(mc[0].Groups["comment"].Value); var score = decimal.Parse(mc[0].Groups["score"].Value); } }
C#中HTML/XML處理及Regex