|
近段時(shí)間在論壇上面興起了一股正則之風(fēng),不論做什么都喜歡用正則 你在后臺(tái)解析json格式字符串,必須要用正則,好吧,你可能不知道用 JavaScriptSerializer類(lèi), 你解析類(lèi)似www.xxx.com?a=a1&b=b2&c=c3的querystring參數(shù),必須用正則,好吧,你也可能不知道string.split方法 你解析html你還必須用正則,好吧,這就真沒(méi)有必要了,因?yàn)樵诮馕鰄tml用到正則的時(shí)候你很多時(shí)候就不得不用到平衡組,你很有可能卡在這里 正則的強(qiáng)大性與通用性就不提了,一般的處理完全夠用了,你完全可以自己去“系統(tǒng)”的學(xué)習(xí)(注:系統(tǒng)學(xué)習(xí)正則),在配上RegexBuddy或者在線(xiàn)的正則(注:附注會(huì)提到內(nèi)容)的工具就可以掌握一些常用的用法 但是去解析html,還是用專(zhuān)業(yè)的庫(kù)去解析吧,雖然條條大路通羅馬,你真沒(méi)必要以鐵人三項(xiàng)的精神去做用正則死嗑html。 其實(shí)解析html的庫(kù)有滿(mǎn)多不錯(cuò)的,如 HtmlAgilityPack , 又或者 Jumony , 以及Java的解析庫(kù)htmlparser(有.net版的),下面列一個(gè)小例子: 地址:http://feedback./ws/eBayISAPI.dll?ViewFeedback2&ftab=AllFeedback&userid=paragad&iid=-1&de=off&items=25&interval=0&mPg=151
抓取評(píng)論區(qū)的:回復(fù)內(nèi)容,購(gòu)買(mǎi)人名字,購(gòu)買(mǎi)時(shí)間 引用:HtmlAgilityPack庫(kù)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HtmlAgilityPack; namespace AnaHtml { class Program { static void Main(string[] args) { HtmlWeb html = new HtmlWeb(); var content = from page in html.Load("http://feedback./ws/eBayISAPI.dll?ViewFeedback2&ftab=AllFeedback&userid=paragad&iid=-1&de=off&items=25&interval=0&mPg=151") //Skip(1)排除標(biāo)題行 where((x,index)=>index%2==0)選取相應(yīng)的內(nèi)容行 .DocumentNode.SelectSingleNode("http://table[@class='FbOuterYukon']").Elements("tr").Skip(1).Where((x, index) => index % 2 == 0) let row = page where row != null select new { Content = row.ChildNodes[1].InnerText, //注意,任何時(shí)候的SelectSingleNode方法都是以整個(gè)document為前提的,個(gè)人覺(jué)得應(yīng)該當(dāng)前的節(jié)點(diǎn)為前擔(dān) Id =row.ChildNodes[2].SelectSingleNode(row.ChildNodes[2].XPath+"http://div[1]//a[1]//span[1]").InnerHtml, Retime = row.ChildNodes[3].InnerText }; foreach (var item in content) { Console.WriteLine("\r\n Content:{0} Id={1} Time={2} ", item.Content, item.Id,item.Retime); } Console.Read(); } } } 整個(gè)結(jié)構(gòu)清晰自然,利用Xpath的來(lái)進(jìn)行選取相當(dāng)方便,輕易就可以抓取內(nèi)容。 附注: 一,正則相關(guān) 1.30分鐘搞定正則(了然正則的基礎(chǔ)知識(shí)點(diǎn)) 2.正則達(dá)人的博客 二,解析庫(kù):
XPath簡(jiǎn)明介紹
<? xml version = "1.0" encoding = "utf-8" ?> < Articles > < Article > < Title > 在ASP.NET中使用Highcharts js圖表 </ title > < Url > http://zhoufoxcn.blog.51cto.com/792419/537324 </ Url > < CreateAt type = "en" > 2011-04-07 </ price > </ Article > < Article > < Title lang = "eng" > Log4Net使用詳解(續(xù)) </ title > < Url > http://blog.csdn.net/zhoufoxcn/archive/2010/11/23/6029021.aspx </ Url > < CreateAt type = "zh-cn" > 2010年11月23日 </ price > </ Article > < Article > < Title > J2ME開(kāi)發(fā)的一般步驟 </ title > < Url > http://blog.csdn.net/zhoufoxcn/archive/2011/06/12/6540223.aspx </ Url > < CreateAt type = "zh-cn" > 2011年06月12日 </ price > </ Article > < Article >
針對(duì)上面的XML文件,我們列出了帶有謂語(yǔ)的一些路徑表達(dá)式,以及表達(dá)式的結(jié)果:
轉(zhuǎn)自=> 周公博客 |
|
|