C#中HTML/XML处理及正则表达式
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:
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);正则表达式抽取
利用正则表达式来抽取信息,其实不同语言的逻辑都一样,语法略有不同。这里不做介绍,仅仅给出一个抽取的例子作为参考。注意每一个匹配部分会用”?<—>”开头来对该Group命名,后面取匹配的数据的时候就可以借助这个名字得到相应的匹配值。
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70725.html