C#超简单爬虫demo

运用正则表达式匹配链接,实现爬取煎蛋网的图片。代码很短,新手值得一试。

不说废话了,直接上图。

在这里插入图片描述
在这里插入图片描述

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace Crawler
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://jandan.net/top-zoo";
            string path = @"D:\Picture\";
            HttpWebRequest webRequest = WebRequest.CreateHttp(url);
            webRequest.Method = "GET";
            webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ";
            var webResponse = webRequest.GetResponse();
            StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
            string str = streamReader.ReadToEnd();
            streamReader.Close();
            if (string.IsNullOrEmpty(str))
            {
                Console.WriteLine("————————-错误—————————");
                Console.ReadKey();
            }
            Regex regex = new Regex("<img.*?src=['|\"](?<Collect>(.*?(?:\\.(?:png|jpg|gif))))['|\"]");
            MatchCollection match = regex.Matches(str);
            WebClient client = new WebClient();
            int name = 0;
            try
            {
                foreach (Match match1 in match)
                {
                    string src = match1.Groups["Collect"].Value;
                    src = "http:"+src;
                    name++;
                    client.DownloadFile(src,path+name+".jpg");
                    Console.WriteLine("\n正在爬取———————" + "|" +src);                  
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("-------------" + ex);
            }
            Console.ReadKey();
        }

    }
}


希望能给有需要的人一些启示和帮助。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值