• C#.Net使用正则表达式抓取百度百家文章列表


        工作之余,学习了一下正则表达式,鉴于实践是检验真理的唯一标准,于是便写了一个利用正则表达式抓取百度百家文章的例子,具体过程请看下面源码:

        一:获取百度百家网页内容

     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         }

        二:通过正则表达式筛选

     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         }

     源码下载

  • 相关阅读:
    随堂练习 shell脚本(五)
    随堂练习 shell脚本(四)
    随堂练习 shell脚本(三)
    马哥博客作业第五周
    JavaScript连载25-正则表达式的匹配分割替换以及贪婪模式
    Java连载130-JDBC编程初步
    C连载15-练习一波转换模式
    Android连载25-强制下线具体实现
    JavaScript连载24-正则表达式
    Java连载129-广播数据包、网络编程总结
  • 原文地址:https://www.cnblogs.com/imhaiyang/p/3983004.html
Copyright © 2020-2023  润新知