简单的爬虫,爬取博客园文章标题

2018-06-18 00:46:52来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

花了几个小时写了一个小程序,没什么技术含量,第一次写博客。本人是个菜鸟,想记录一下自己的学习。

运行效果如图:

 
代码如下:
            string url = "https://www.cnblogs.com/";
            int pagNum = 10;
            string html = "";
            //string pater = "(<a class=\"titlelnk\" href=\"[\\s\\S]*\" target =\"_blank\">)([\\s\\S]*)(</a>)";
            string pater = "<a class=\"titlelnk\" href=\"(.*?)\" target=\"_blank\">(.*?)</a>";
            Regex regex = new Regex(pater);

            int num = 0;
            for (int i = 1; i < pagNum; i++)
            {
           string  url2 = url + "#p" + i;
                try
                {
                    WebRequest request = WebRequest.Create(url2);
                    Stream stream = request.GetResponse().GetResponseStream();
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = reader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.ReadKey();
                }
              
                if (!string.IsNullOrEmpty(html))
                {
                    //  Match match = Regex.Match(html, pater);
                    foreach (Match ma in regex.Matches(html))
                    {
                        Match math = Regex.Match(ma.Value,pater);
                        string title = math.Groups[2].Value;
                        num++;
                        Console.WriteLine("" + num + "个标题:\b" +title);
                        File.AppendAllText(@"d:\1.txt",title+ "\r\n");
                    }
                   
                }
            }
            Console.ReadKey();

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:C#核心语法-泛型(详细讲解泛型方法、泛型类、泛型接口、泛型约

下一篇:【VB.NET】通过 IPIP.NET 数据库来查询IP地址