C#.Net使用Regex抓取百度百家文章列表

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   使用   ar   strong   

    工作之餘,學習了一下Regex,鑒於實踐是檢驗真理的唯一標準,於是便寫了一個利用Regex抓取百度百家文章的例子,具體過程請看下面源碼:

    一:擷取百度百家網頁內容

 1 public List<string[]> GetUrl() 2         { 3             try 4             { 5                 string url = "http://baijia.baidu.com/"; 6                 WebRequest webRequest = WebRequest.Create(url); 7                 WebResponse webResponse = webRequest.GetResponse(); 8                 StreamReader reader = new StreamReader(webResponse.GetResponseStream()); 9                 string result = reader.ReadToEnd();10                 reader.Close();11                 webResponse.Close();12                 return AnalysisHtml(result);13             }14             catch (Exception ex)15             {16                 throw ex;17             }18         }

    二:通過Regex篩選

 1 public List<string[]> AnalysisHtml(string htmlContent) 2         { 3             List<string[]> list = new List<string[]>(); 4             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>"; 5             Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant); 6             if (regex.IsMatch(htmlContent)) 7             { 8                 MatchCollection matchCollection = regex.Matches(htmlContent); 9                 foreach (Match match in matchCollection)10                 {11                     string[] str = new string[3];12                     str[0] = match.Groups[1].Value;//擷取到的是列表資料的標題13                     str[1] = match.Groups[2].Value;//擷取到的是內容14                     str[2] = match.Groups[3].Value;//擷取到的是連結到的地址15                     list.Add(str);16                 }17             }18             return list;19         }

 源碼下載

C#.Net使用Regex抓取百度百家文章列表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.