本文實(shí)例講述了C#.Net基于正則表達(dá)式抓取百度百家文章列表的方法。分享給大家供大家參考,具體如下:
工作之余,學(xué)習(xí)了一下正則表達(dá)式,鑒于實(shí)踐是檢驗(yàn)真理的唯一標(biāo)準(zhǔn),于是便寫了一個(gè)利用正則表達(dá)式抓取百度百家文章的例子,具體過程請(qǐng)看下面源碼:
一、獲取百度百家網(wǎng)頁(yè)內(nèi)容
public List<string[]> GetUrl(){  try  {    string url = "http://baijia.baidu.com/";    WebRequest webRequest = WebRequest.Create(url);    WebResponse webResponse = webRequest.GetResponse();    StreamReader reader = new StreamReader(webResponse.GetResponseStream());    string result = reader.ReadToEnd();    reader.Close();    webResponse.Close();    return AnalysisHtml(result);  }  catch (Exception ex)  {    throw ex;  }}二、通過正則表達(dá)式篩選
public List<string[]> AnalysisHtml(string htmlContent){  List<string[]> list = new List<string[]>();  string strPattern = "<h3><a//s*.*>(?<Title>[^<]+)</a></h3>.*//s*<p//s*class=/"feeds-item-text/">(?<Abstract>[^<]+)<a//s*href=/"(?<Url>.*)/"http://s*target=/"_blank/"http://s*class=/"feeds-item-more/"http://s*mon=/".*//s*/">.*//s*</a></p>";  Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant);  if (regex.IsMatch(htmlContent))  {    MatchCollection matchCollection = regex.Matches(htmlContent);    foreach (Match match in matchCollection)    {      string[] str = new string[3];      str[0] = match.Groups[1].Value;//獲取到的是列表數(shù)據(jù)的標(biāo)題      str[1] = match.Groups[2].Value;//獲取到的是內(nèi)容      str[2] = match.Groups[3].Value;//獲取到的是鏈接到的地址      list.Add(str);    }  }  return list;}附:完整實(shí)例代碼點(diǎn)擊此處本站下載。
PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測(cè)試工具:
http://tools.VeVB.COm/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.VeVB.COm/regex/create_reg
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#正則表達(dá)式用法總結(jié)》、《C#編碼操作技巧總結(jié)》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》及《C#程序設(shè)計(jì)之線程使用技巧總結(jié)》
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選