C#.Net基于正則表達式抓取百度百家文章列表的方法示例
本文實例講述了C#.Net基于正則表達式抓取百度百家文章列表的方法。分享給大家供大家參考,具體如下:
工作之余,學(xué)習(xí)了一下正則表達式,鑒于實踐是檢驗真理的唯一標準,于是便寫了一個利用正則表達式抓取百度百家文章的例子,具體過程請看下面源碼:
一、獲取百度百家網(wǎng)頁內(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; } }
二、通過正則表達式篩選
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>.*)\"\\s*target=\"_blank\"\\s*class=\"feeds-item-more\"\\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ù)的標題 str[1] = match.Groups[2].Value;//獲取到的是內(nèi)容 str[2] = match.Groups[3].Value;//獲取到的是鏈接到的地址 list.Add(str); } } return list; }
附:完整實例代碼點擊此處本站下載。
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#正則表達式用法總結(jié)》、《C#編碼操作技巧總結(jié)》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》及《C#程序設(shè)計之線程使用技巧總結(jié)》
希望本文所述對大家C#程序設(shè)計有所幫助。
相關(guān)文章
C#/VB.NET實現(xiàn)將XML轉(zhuǎn)為PDF
可擴展標記語言(XML)文件是一種標準的文本文件,它使用特定的標記來描述文檔的結(jié)構(gòu)以及其他特性。本文將利用C#實現(xiàn)XML文件轉(zhuǎn)PDF?,需要的可以參考一下2022-03-03