使用WebClient下载网页,用正则匹配需要的内容

WebClient是一个操作网页的类

webClient web=new  WebClient();

web.DownloadString(网页的路径,可以是本地路径);--采用的本机默认的编码格式  返回值为string
如果网页采用用的是utf8的话用   web.DownloadData(与DownloadString用法一样) 的返回值为byte[](字节数组)

 

 

一个简单的匹配图片下载的代码:

static void Main(string[] args)

        {

            //操作网页的一个类

            WebClient web = new WebClient();

            //<img src="https://gss3.bdstatic.com/84oSdTum2Q5BphGlnYG/timg?wapp&amp;quality=80&amp;size=b65_65&amp;subsize=20480&amp;cut_x=0&amp;cut_w=0&amp;cut_y=0&amp;cut_h=0&amp;sec=1369815402&amp;srctrace&amp;di=9f6cdc0624f7b25832f34ad393db5063&amp;wh_rate=null&amp;src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fpic%2Fitem%2Fe824b899a9014c084548ecd9087b02087bf4f45f.jpg"/>

            byte[] buffer = web.DownloadData(@"https://tieba.baidu.com/f?kw=%E5%A5%BD%E7%9C%8B%E7%9A%84%E5%9B%BE%E7%89%87&fr=fenter&prequery=%E5%A5%BD%E7%9C%8B%E7%9A%84%E5%9B%BE%E7%89%87%E5%A4%A7%E5%85%A8%E5%B8%A6%E5%AD%97");

            //将字节转换成字符串,该网页采用的是utf8编码格式

            string html = Encoding.UTF8.GetString(buffer);

            MatchCollection mc = Regex.Matches(html, @"<img.+?(?<priSrc>https.+?\.jpg).+?>");

            int i = 0;

            foreach (Match item in mc)

            {

                i++;

                Console.WriteLine(item.Value);

                string uri = item.Groups["priSrc"].Value;

                string path = Path.Combine(@"C:\Users\Administrator\Desktop\images", +i+".jpg");

                            //用DownloadFile下载文件

                web.DownloadFile(uri, path);

            }

          

            Console.ReadKey();

        }

 

 

读取之后转化为字符串(自己转把,不写了)就能把网页拿过来搞事情了

posted @ 2017-11-08 11:42  fabc  阅读(379)  评论(0编辑  收藏  举报